Javascript – Convert Number to int? incompatible types found : void required: int

google mapsjavajavascriptjsp

I am writing an application to get latitude, longitude of a position in a google map using java and javascript.

The below code part gives an error:

code(It's a part of a jsp file):

<script type="text/javascript">
  var map;

  //Initialization & some more code goes here

  function centerChanged() {
    <%
        int lat=0,lng=0;
        lat=%>map.getCenter().lat();<%
        lng=%>map.getCenter().lng();<%
        //request.setAttribute("lat", lat);
        //request.setAttribute("lng", lng);
    %>    
  }

From the above code, these are the two lines that cause the error:

    lat=%>map.getCenter().lat();<%
    lng=%>map.getCenter().lng();<%

Additional Information:

map.getCenter().lat() << This will return a Number as mentioned in google maps API:

This is the error I am getting:

org.apache.jasper.JasperException: PWC6033: Error in Javac compilation
for JSP

PWC6197: An error occurred at line: 81 in the jsp file: /maptest.jsp
PWC6199: Generated servlet error: string:///maptest_jsp.java:127:
incompatible types found : void required: int

PWC6197: An error occurred at line: 82 in the jsp file: /maptest.jsp
PWC6199: Generated servlet error: string:///maptest_jsp.java:130:
incompatible types found : void required: int

Can anyone please tell what is wrong?

Best Answer

You are trying to dynamically insert a value from Javascript into JSP. The mistake is that JSP is executed on the server side, whilst Javascript on client side.

What you wrote there is equal to Java code:

out.write("function centerChanged() {");
int lat=0,lng=0;
lat=;
out.write("map.getCenter().lat();");
lng=;
out.write("map.getCenter().lng();");
//request.setAttribute("lat", lat);
//request.setAttribute("lng", lng);
out.write("}");

Get it? Whatever is surrounded by <%%> is pure Java code, whatever is outside of it, is printed out, hence your exception.

To work around it, you need to change the logic how you retrieve the client-side Javascript values in your server-side JSP code.

Related Topic