Google Maps API use zoom level and center position from local storage values to adjust map on page load

Viewed 25

I am working with a WordPress/jQuery/Google Maps setup to display a map of listings to users.

The jQuery.goMap.map code is used to load in the Google Maps instance used on the WordPress plugin.

I have wrote the following functions to store and load the latitude, longitude, and zoom level with local storage. The storing of the lat/lng and zoom levels is working, and the loading of the zoom level is working, but I cannot get the map to center on the loaded latitude and longitude position.

I have tried using bounds.extend(latLng); and jQuery.goMap.map.fitBounds(bounds); in the loadUserZoom function, but the result is a fully zoomed in map. This means the stored zoom level value is being ignored.

The current functioning code can be tested here.

The Clear text link in the header navigation can be used to clear the local storage values from the browser. This is implemented for testing purposes.

Any assistance is greatly appreciated.

Function: storeUserZoom

function storeUserZoom() {
  let zoom = jQuery.goMap.map.getZoom();
  localStorage.setItem( 'zoom', zoom);
  let center = jQuery.goMap.map.getCenter();
  let lat = center.lat();
  let lng = center.lng();
  let latLng = {
    lat: lat,
    lng: lng
  }
  localStorage.setItem( 'latLng', JSON.stringify(latLng));
}

Function: loadUserZoom

function loadUserZoom() {
  if (localStorage.getItem( 'zoom' )) {
    let zoom = parseInt(localStorage.getItem( 'zoom' ));
    console.log(zoom);
    // Logs correct zoom level
    let latLng = JSON.parse(localStorage.getItem( 'latLng' ));
    console.log(latLng);
    // Logs Object { lat: 51.69124213478852, lng: -113.2478200914128 }
    jQuery.goMap.map.setZoom(zoom);
    jQuery.goMap.map.setCenter(latLng);
    // latLng used is incorrect
  }
}
1 Answers

I believe I have zeroed in on the problem by adjusting how the loadUserZoom function was executed in the initMap function.

The loadUserZoom function was wrapped in a Google Maps listen once event listener when the map was idle. The code is included below.

google.maps.event.addListenerOnce(jQuery.goMap.map, 'idle', function() {
  loadUserZoom();
});

I had it set initially to addListener, which seemed to conflict with the required functionality. I assume this meant it was execute regularly whenever the map was in an idle state.

My updated loadUserZoom function is included below.

function loadUserZoom() {
  if (localStorage.getItem( 'zoom' )) {
    let zoom = parseInt(localStorage.getItem( 'zoom' ));
    let latLng = JSON.parse(localStorage.getItem( 'latLng' ));
    jQuery.goMap.map.setZoom(zoom);
    jQuery.goMap.map.setCenter(latLng);
  }
}
Related