简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM