How can I change the location in a map using javascript and google maps?

2k views Asked by At

I'm trying to change the center of a map using an each loop for going to different places, however when I execute the code the map does not show all locations instead the map show the first and last location, I will be grateful if you can help me with this problem.

This is the code:

    var a = new google.maps.LatLng(8.8013, -74.72538);
    var b = new google.maps.LatLng(1.0619, -73.2558);
    var c = new google.maps.LatLng(12.5872, -81.7025);
    var d = new google.maps.LatLng(3.2719, -73.0877);

    var locations = new Array(a, b, c, d);
    var mapProp = {
        center: new google.maps.LatLng(5.0619, -70.2558),
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);

    function initialize() {
        goToLocations(locations);
    }
    google.maps.event.addDomListener(window, 'load', initialize);   

    function goToLocations(locations) {
        $.each(locations, function (index, location) {
            goToLocation(location);
        });
    }

    function goToLocation(location) {
      // here I can not see all locations 
        window.setTimeout(map.setCenter(location), 5000);        
    }
<html>  

  <body>
    
    <script src="http://maps.google.com/maps/api/js?sensor=true" type="text/javascript">       </script>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    
    <h1>Map that go to different locations </h1>
    <div id="googleMap" style="width: 500px; height: 380px"></div>
    
  </body>
  
</html>

1

There are 1 answers

1
Llogari Casas On BEST ANSWER

Your function is working fine and it is actually showing all the cities you have on your array. However, we are not able to see it. The function is exectuted so fast that we are only able to see the first and the last one.

Try to put a Timeout inside the $.each function and it will work:

$.each(locations, function (index, location) {
   window.setTimeout(function(){  
      goToLocation(location);
   }, 1000);
});