Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

provide a list of latitudes and longitudes to my google map to visualize them with markers

In my project, I have a database containing a list of latitudes and longitudes, corresponding to several addresses, and I want to take them from this database and pass them to a javascript code that will show all these addresses in a map using markers. So far I got all the list from the database. and I was able to visualize one and only one address in the map by using it's latitude and longitude. So what I am struggeling with now is doing so for multiple addresses. Here is the code that I came up with so far:

      function initialize() {
          var myLatlng = new google.maps.LatLng(locations[0], locations[1]);
          var myOptions = {
              zoom: 4,
              center: myLatlng,
              mapTypeId: google.maps.MapTypeId.ROADMAP
          }
          map = new google.maps.Map(document.getElementById("map"), myOptions);
          var marker = new google.maps.Marker({
              position: myLatlng,
              map: map,
              title: "Fast marker"
          });
      }

      google.maps.event.addDomListener(window, 'load', initialize);

locations is the list of my latitudes and longitudes, and it goes like this:

locations[0]: latitude 1  
locations[1]: longitude 1  
locations[2]: latitude 2  
locations[3]: longitude 2    etc..

Now I know there is supposed to be some kind of loop but I couldn't manage to do it.

Thanks in advance!

P.S: This is my first question so don't judge my accept rate! :)

like image 225
zahi daoui Avatar asked Oct 06 '22 14:10

zahi daoui


2 Answers

You just need to write a for loop as follows:

function initialize() {
  var myOptions = {
    zoom: 4,
    center: new google.maps.LatLng(locations[0], locations[1]),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map"), myOptions);
  for (var i = 0, ln = locations.length; i < ln; i += 2) {
    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(locations[i], locations[i + 1]);
      map: map,
      title: "Fast marker"
    });
  }
}

google.maps.event.addDomListener(window, 'load', initialize);​
like image 168
Stephen Young Avatar answered Oct 10 '22 03:10

Stephen Young


You can write a simple for loop to iterate through locations. Increment two at a time:

var map = new google.maps.Map(document.getElementById("map"), myOptions);

for (var i=0 ; i < locations.length-1 ; i+=2) {

    var lat = locations[i];
    var lng = locations[i+1];

    var myLatlng = new google.maps.LatLng(lat, lng);
    var myOptions = {
          zoom: 4,
          center: myLatlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var marker = new google.maps.Marker({
          position: myLatlng,
          map: map,
          title: "Fast marker"
    });
}
like image 32
McGarnagle Avatar answered Oct 10 '22 04:10

McGarnagle