Skip to content Skip to sidebar Skip to footer

How To Pass Variables From Java Class To Java Script

I have been trying to generate a map with Latitude & Longitude ,I am fetching these lat & lon from MYSQL DB. I have a java class which will connect to database & retri

Solution 1:

Your Java code should be in a servlet, you should then add your lat/lng results to a container and serialize to JSON, example with GSON:

classResult {
     double lat;
     double lng;

     Result(double l, double ll) {
         this.lat = l;
         this.lng = ll;
     }
}

List<Result> results = new ArrayList<>();
while (rs.next()) {
    results.add(newResult(rs.getInt("latitude"), rs.getInt("longitude"))); 
}

final TypeToken<List<Result>> resultsType = new TypeToken<List<Result>>() {};
response.getWriter().write(newGson().toJson(results, resultsType.getType()))

And then in your javascript, assuming this was called with Ajax, you can consume the json:

var markers = [];
for (var i = 0; i < responseJSON.length) {
    markers.push(responseJSON[i].lat + ', ' + responseJSON[i].lng)
}

Solution 2:

With your question, it seems you are trying to add Marker in a Map. Anyway, here is the solution in Steps:

Step 1: In your controller, set a String :

String data ="{\"lat\":"+Lattitude+",\"Longitude\":"+Longitude+"}";
request.getSession(false).setAttribute("latLong", data);

Step 2: In your JSP page, you can obtain the same String as

<script>var latLon = <%=session.getAttribute("latLong") %>;

// You are done.

In case if you are trying to get the lat-long once JSP is loaded. Then you must go with Ajax call request and fetch the above "latLong" as a response in JSON. Updated: Incase you wanna to add marker, then below will be the logic.

Suppose user clicked at one location on map and you already have map and layers for the same. In the following example there is map which is the object of OpenLayers.Map.

map.events.register("click", map, function(e) {

                            var positionN = this.events.getMousePosition(e);

                            var lonlat = map.getLonLatFromPixel(positionN);
                            var TempPoint = new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat);
                            var iconAnnotation = new OpenLayers.Icon(OpenLayers.ImgPath + '../../css/img/icon.png');
                            var feature = new OpenLayers.Feature.Vector(TempPoint,{icon:iconAnnotation,labelText: "",markerId:"r", labelColor:"red"});
                            AnnotationLayer.addFeatures([feature]);

                    });

Post a Comment for "How To Pass Variables From Java Class To Java Script"