javascriptjavajspjsp-tagsjava-server

How can i add Multiple Markers on Google Map using SQL as a Database and JSP?


i have succesfully added multiple markers on google map using static data

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
 </script> 
 <script type="text/javascript">
  var delay = 100;
  var infowindow = new google.maps.InfoWindow();
  var latlng = new google.maps.LatLng(21.0000, 78.0000);
  var mapOptions = {
    zoom: 5,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var geocoder = new google.maps.Geocoder(); 
  var map = new google.maps.Map(document.getElementById("map"), mapOptions);
  var bounds = new google.maps.LatLngBounds();

  function geocodeAddress(address, next) {
    geocoder.geocode({address:address}, function (results,status)
      { 
         if (status == google.maps.GeocoderStatus.OK) {
          var p = results[0].geometry.location;
          var lat=p.lat();
          var lng=p.lng();
          createMarker(address,lat,lng);
        }
        else {
           if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
            nextAddress--;
            delay++;
          } else {
                        }   
        }
        next();
      }
    );
  }
 function createMarker(add,lat,lng) {
   var contentString = add;
   var marker = new google.maps.Marker({
     position: new google.maps.LatLng(lat,lng),
     map: map,
           });

  google.maps.event.addListener(marker, 'click', function() {
     infowindow.setContent(contentString); 
     infowindow.open(map,marker);
   });

   bounds.extend(marker.position);

 }
  var locations = [
           'New Delhi, India',
           'Mumbai, India',
           'Bangaluru, Karnataka, India',
           'Hyderabad, Ahemdabad, India',
           'Gurgaon, Haryana, India',
           'Cannaught Place, New Delhi, India',
           'Bandra, Mumbai, India',
           'Nainital, Uttranchal, India',
           'Guwahati, India',
           'West Bengal, India',
           'Jammu, India',
           'Kanyakumari, India',
           'Kerala, India',
           'Himachal Pradesh, India',
           'Shillong, India',
           'Chandigarh, India',
           'Dwarka, New Delhi, India',
           'Pune, India',
           'Indore, India',
           'Orissa, India',
           'Shimla, India',
           'Gujarat, India'
  ];
  var nextAddress = 0;
  function theNext() {
    if (nextAddress < locations.length) {
      setTimeout('geocodeAddress("'+locations[nextAddress]+'",theNext)', delay);
      nextAddress++;
    } else {
      map.fitBounds(bounds);
    }
  }
  theNext();

</script>

Now i want to add multiple markers on google map but want to retrive all the values in locations from SQL database. i have tried to pass resultset as a array to JavaScript. but i can only call initMap() method only once a click. so not multiple markers are showing on Map. Only one marker is showing at a time not Multiple. and also i dont want to show this markers on any onclick method. i have also used onload method but resultset.next() not retrieving throughly all values of database.

Every help would be appreciated.

Note : Please sugges only how to add markers using values which are stored in Database. Not static.


Solution

  • yeah.. here i got my mistake.. i am creating Markers but not holding it. so for that i have created one array of markers.. and pushed all markers in that.. because of that i am holding every marker i am creating using database..

    here my all working code goes..

    <!DOCTYPE html>
    <%@ page import = "java.io.*,java.util.*,java.sql.*"%>
    <%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
             pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>    
    <html>
    
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title>Google Maps APIs</title>
    
            <link href="style.css" rel="stylesheet">
    
            <style>
                html,
                body {
                    height: 200px;
                    width: 100%;
                    margin: 0;
                    padding: 0;
                }
            </style>
        </head>
        <body onload="initMap2();">
    
    
            <sql:setDataSource
                var="myDS"
                driver="com.mysql.jdbc.Driver"
                url="jdbc:mysql://localhost:3306/mess"
                user="root" password=""
                />
    
            <sql:query var="listUsers"	dataSource="${myDS}">
                SELECT * FROM latlang;
            </sql:query>
    
            <div align="center">
                <select id="messname">
                    <c:forEach var="user" items="${listUsers.rows}">
                        <option><c:out value="${user.messname}" /></option1>
                        </c:forEach>
                </select>
                <select id="lat">
                    <c:forEach var="user" items="${listUsers.rows}">
                        <option><c:out value="${user.lat}" /></option>
                    </c:forEach>
                </select>
                <select id="lang">
                    <c:forEach var="user" items="${listUsers.rows}">
                        <option><c:out value="${user.lang}" /></option2>
                        </c:forEach>
    
                </select>
    
                <c:forEach var="user" items="${listUsers.rows}">
    
                    <button><a onclick="showMarkers();">${user.messname}</a></button>
                    </c:forEach>		
    
            </div>               
            <script>
            </script>
            <sql:query var="result" dataSource="${myDS}" >
    
                SELECT * from latlang;
            </sql:query>
            <script>
    
    
                var map;
          var markers = [];
    
          function initMap() {
              
              var mrks = [
                <c:forEach var="row" items="${result.rows}">
                        ['<c:out value="${row.messname}" />',
                    <c:out value="${row.lat}" />,
                    <c:out value="${row.lang}" />,
                        ],
                </c:forEach>];
    
            //var haightAshbury = {lat: 37.769, lng: -122.446};
    
            map = new google.maps.Map(document.getElementById('map'), {
              zoom: 12,
              center: {lat: 18.5204, lng: 73.8567},
              mapTypeId: 'terrain'
            });
    
            // This event listener will call addMarker() when the map is clicked.
              
            // Adds a marker at the center of the map.
            for(var i=0; i<mrks.length; i++)
            {   
                    var pos = new google.maps.LatLng(mrks[i][1], mrks[i][2]);
                    addMarker(pos);
            }
         }
    
          // Adds a marker to the map and push to the array.
          function addMarker(location) {
            var marker = new google.maps.Marker({
              position: location,
              map: map
            });
            markers.push(marker);
          }
    
          // Sets the map on all markers in the array.
          function setMapOnAll(map) {
            for (var i = 0; i < markers.length; i++) {
              markers[i].setMap(map);
            }
          }
    
          // Removes the markers from the map, but keeps them in the array.
          
    
          // Shows any markers currently in the array.
          function showMarkers() {
            setMapOnAll(map);
          }
    
          // Deletes all markers in the array by removing references to them.
            </script>
    
            <p><td>  </td></p>
    
    <input type="text" id="searchvalue">
    
    <input type="button" id="btn" value="Click" onclick="">        
    <%-- //>--%>
    
    <div id="map" style="height:200px; width:200px"></div>
    <p>
    
    
        <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBN1fnarI5qrCYI7gS6ksuX3L7jHGTq2MY&callback=initMap"></script>
    </body>
    
    </html>

    thanks for helping..!!!