Search code examples
javascriptgoogle-mapsgoogle-maps-api-3

Google Maps Api :set the center of map to different coordinates after rendering


I want to change the center of google map after some time interval so that it can focus on certain areas of the whole continent having markers showing restaurants branches. I have successfully rendered the map with markers. What i am having problem is changing the center looping through a list of latitude and longitude. I am trying to do something like this.

var lat[];
        var lang[];

            function moveToLocation(){
                var center = new google.maps.LatLng(lat, lng);
                map.panTo(center);
            }

             setInterval(moveToLocation, 3000);  

Solution

  • From this related question: Google maps dynamically zooming in different locations

    proof of concept fiddle

    code snippet:

    var map;
    
    function initialize() {
      map = new google.maps.Map(
        document.getElementById("map_canvas"), {
          center: new google.maps.LatLng(37.4419, -122.1419),
          zoom: 8,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
    
      var places = [
        [52, -1],
        [52, -2],
        [53, -3],
        [53, -5],
        [54, -4],
        [54, -6]
      ];
    
      var index = 0;
      zoomInterval = setInterval(function() {
        var lat = places[index][0];
        var lng = places[index][1];
        index = (index + 1) % places.length;
        map.setCenter(new google.maps.LatLng(lat, lng));
    
      }, 5000);
    
    
    }
    google.maps.event.addDomListener(window, "load", initialize);
    html,
    body,
    #map_canvas {
      height: 100%;
      width: 100%;
      margin: 0px;
      padding: 0px
    }
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
    <div id="map_canvas"></div>