Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move google map center javascript api

In my project I want to move the center of the map to new coordinates. This is the code I have for the map

function initialize() {     var mapOptions = {       center: new google.maps.LatLng(0, 0),       zoom: 4,       mapTypeId: google.maps.MapTypeId.ROADMAP     };     var map = new google.maps.Map(document.getElementById("map_canvas"),         mapOptions);   }   function moveToLocation(lat, lng){      var center = new google.maps.LatLng(lat, lng);      var map = document.getElementById("map_canvas");      map.panTo(center);    } 

The moveToLocation function does get called but the map does not re center. Any idea what I'm missing?

like image 512
taormania Avatar asked Oct 02 '12 22:10

taormania


1 Answers

Your problem is that in moveToLocation, you're using document.getElementById to try to get the Map object, but that only gets you an HTMLDivElement, not the google.maps.Map element you're expecting. So your variable map has no panTo function, which is why it doesn't work. What you need to is squirrel the map variable away somewhere, and it should work as planned. You can just use a global variable like so:

window.map = undefined;      // global variable  function initialize() {   const mapOptions = {     center: new google.maps.LatLng(0, 0),     zoom: 4,     mapTypeId: google.maps.MapTypeId.ROADMAP   };   // assigning to global variable:   window.map = new google.maps.Map(     document.getElementById("map_canvas"), mapOptions); }  function moveToLocation(lat, lng){   const center = new google.maps.LatLng(lat, lng);   // using global variable:   window.map.panTo(center); } 

See working jsFiddle here: http://jsfiddle.net/fqt7L/1/

like image 112
Ethan Brown Avatar answered Sep 23 '22 19:09

Ethan Brown