Naomi Naomi - 3 months ago 6
jQuery Question

Update map location when clicking a button

I am using google maps on my website to display 2 locations. I want one map and for the map to update when I press a button for the different locations. This is the JS code.

var map;
var lat = 53.4779168;
var lng = -2.2338925;

function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: { lat: lat, lng: lng }, zoom: 17 }); };
$(document).ready(function() {


$("#picadilly").click(function() {
lat = 53.4779168;
lng = -2.2338925;
});


$("#didsbury").click(function() {
lat = 53.410346;
lng = -2.229417;

});


});


It seems to be register that I'm pressing the button but it doesn't update the location of the map. Any ideas?

Answer

You can simply move the map with map.setCenter(LatLng) under click event function. This method will not use any other markers and will not erase existing markers. You could also move the map via the panTo(LatLng) function. Both methods are also available after the map has been initialized.

$("#picadilly").click(function() {
     lat = 53.4779168;
     lng = -2.2338925;
     map.setCenter({lat:lat , lng:lng});
 });


 $("#didsbury").click(function() {
     lat = 53.410346;
     lng = -2.229417;
     map.setCenter({lat:lat , lng:lng});
 });

Here is the documentation for these methods.