0

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 & retrieve lat,lon ,So i need to pass these values to a JavaScript which has a code to generate map.

In the Javascript i have a function called addmarker() Which has lat & lon.The Actual Requirement is I have to pass lat,lon form the java class to Javascript.

Here is my java code:

            Connection conn = null;  
            PreparedStatement pst = null;  
            ResultSet rs = null;  
      
            String url = "jdbc:mysql://localhost:3306/";  
            String dbName = "db5";  
            String driver = "com.mysql.jdbc.Driver";  
            String userName = "root";  
            String password = "root";  
            
            
            
             try {  
                    Class.forName(driver).newInstance();  
                    conn = DriverManager.getConnection(url + dbName, userName, password);  
      
              
            
                pst = conn.prepareStatement("select latitude,longitude  from nidgis where nidevid=?");
                pst.setString(1, n);
                rs = pst.executeQuery();
              
                while(rs.next())
                 {
                      rs.getInt("latitude");  
                      rs.getInt("longitude");  
                }
               
            }
            catch (Exception e) 
            {  
                System.out.println(e);  
            }

Here is my JS code:

      <script>
             function addMarker() 
             {


               var vehicle = new MQA.Poi({
               lat: vehicle_lat,
               lng: vehicle_lng,
             });
              var icon = new MQA.Icon(
             'https://cdn2.iconfinder.com/data/icons/gpsmapicons   /blue/gpsmapicons07.png',
              35, 42);
             vehicle.setIcon(icon);
            vehicle.setKey("abc");
             map.addShape(vehicle);
           vehicle.setRolloverContent("Vehicle # KA05 9999");
         }

                 MQA.EventUtil.observe(window, 'load', function() {

              /*Create an object for options*/
             var options={
                    elt:document.getElementById('map'),        /*ID of element on the page where you want the map added*/
                    zoom:10,                                   /*initial zoom level of map*/
                    latLng:{lat:39.743943, lng:-105.020089},   /*center of map in latitude/longitude*/
                    mtype:'map'                                /*map type (map)*/
               };

                /*Construct an instance of MQA.TileMap with the options object*/
                 window.map = new MQA.TileMap(options);

                MQA.withModule('geocoder', function() {
              /*Executes a geocode and adds result to the map*/
             map.geocodeAndAddLocations("Denver CO");
            });
            });
              </script>
              <body>

              <div id='map' style='width:1560px; height:730px;'></div>
              <button id="getBasicSample" onclick="addMarker();">show veh1</button> 

             </body>
2
  • is there anything you have tried yet? your code gives no context. i.e. where is the java class, a servet? Commented Jan 27, 2015 at 6:56
  • No I dont know how to pass lat laon from java class to javascript,My java code i have mentioned above which will connect to db & fetch records Commented Jan 27, 2015 at 6:59

2 Answers 2

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:

class Result {
     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(new Result(rs.getInt("latitude"), rs.getInt("longitude"))); 
}

final TypeToken<List<Result>> resultsType = new TypeToken<List<Result>>() {};
response.getWriter().write(new Gson().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)
}
Sign up to request clarification or add additional context in comments.

Comments

0

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]);

                    });

8 Comments

yeah I want to display the markers after the map is loaded,so How to do that I am new to JSON
I updated my solution and also you need to visit the Stackoverflow's site gis.stackexchange.com
Sir I dont want any lat,lon position .I want to pass the lat lon which are retived from DB & I want to pass those to a JAVA SCRIPT which has a function called add marker ,Once the map is loaded The user clicks the showveh1 button,Then all the Lat Lon should be passed to this JS
I didn't understand your requirement. Please be elaborate. As you have both the solutions,
I have a java class which will connect to Mysql DB & Retrieve the latitude ,longitude from a table ,Now The retrieved values should be passed to a JS .This JS has a code to display a map.In this i have a button called show vehicle Button.If the user clicks this button ,I will pass the lat,lon from my java class to a function in Javascript .
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.