views:

32

answers:

1

I have been searching high and low for a solution to this problem. I fetch dynamic positions of markers and show the map positioned and zoomed baased on the City that has been selected in my application. If I then scroll or zooom the Google map and then request an update of the markers position (by fetching the xml) I loose the new position and zoom I was at. How do I make the function check what the current getCenter and getZoom is to use in the reload of the map ?

function load() {

 if(map) { // Does not work
  var lat = map.getCenter().lat();  
     var lng = map.getCenter().lng();
      var zoom = map.getZoom();
 } else {
  var lat = '<?=$Lat?>';
  var lng = '<?=$Lon?>';
  var zoom = <?=$zoom?>;
 }
 var map_options = {
  center: new google.maps.LatLng(lat,lng),
  zoom: zoom,
  mapTypeId: '<?=$map_type?>'
 };

 var map = new google.maps.Map(document.getElementById("map"), map_options);
 var infoWindow = new google.maps.InfoWindow;

    << Other marker creating code here that works fine >>

}
A: 

remove the var? to make the lat,lng, zoom global var

if(map) { // Does not work
  lat = map.getCenter().lat();  
  lng = map.getCenter().lng();
  zoom = map.getZoom();
 } else {
  lat = '<?=$Lat?>';
  lng = '<?=$Lon?>';
  zoom = <?=$zoom?>;
 }

UPDATE move the var map outside of function load() {} something like this:

var map, lat, lng, zoom;
function load(){...map = new google.maps.Map(document.getElementById("map"), map_options);

...}

let me explain this shortly

  1. when page is loaded var map is initiated as "nothing/null", therefore if(map) will be false then use the lat,lng,zoom from your PHP

  2. after map = new google.maps.Map(document.getElementById("map"), map_options); , map holders the js object of gmap.

  3. then load(){...} is called again if(map) is true then the block will be executed
jebberwocky
Thanks for suggestions, but I don't really understand. I am more a PHP programmer, so am struggling with javascript. The reason I can see the if(map) is never returned true is the code "var map = new google.maps.Map(document.getElementById("map"), map_options);" comes after, but I could be mislead by PHP ideas. I have a button on the page that calls load() function. I need to try get the current position and zoom before I start initializing the map again.
DRAllan
hi DRAllan my answer is updated. hope it helps
jebberwocky