简体   繁体   中英

How can i make the marker zoom in when it's clicked?

var neighborhoods = [{lat: 29.988097, lng: 31.442075},];
var marker = [];
var map;
function myMap() {
    map = new google.maps.Map(document.getElementById('googleMap'), {
      zoom: 13,
      center: {lat: 30.024710, lng: 31.446871}
    });
}
function drop() {
    clearMarker();
    for (var i = 0; i < neighborhoods.length; i++) {
      addMarkerWithTimeout(neighborhoods[i], i * 200);  
    }
}
function addMarkerWithTimeout(position) {
    marker.push(new google.maps.Marker({
        position: position,
        map: map,
        animation: google.maps.Animation.DROP
     }))
};
function zoom(){
for (var i = 0; i < marker.length; i++){
    marker[i].addListener('click',function(){
        map.setZoom(15);
    })
}
}
function clearMarker() {
    for (var i = 0; i < marker.length; i++) {
      marker[i].setMap(null);
    }
    marker = [];
};

i don't know why it's not zooming in when clicking the marker . Or is there any other function can i use to make this happend because every thing is going well with this code except this problem

The code you provided is not complete. So I can only guess.

I think the key problem is when to add the listener:

marker[i].addListener('click',function(){
    map.setZoom(15);
})

I guess the timing you run your zoom() is not right. You should add the listener when the marker is created (or before someone click on those markers).

If you add every marker with addMarkerWithTimeout() , I'd recommend to remove the function zoom() . And attach the listener in addMarkerWithTimeout() instead:

var neighborhoods = [{lat: 29.988097, lng: 31.442075},];
var marker = [];
var map;
function myMap() {
    map = new google.maps.Map(document.getElementById('googleMap'), {
      zoom: 13,
      center: {lat: 30.024710, lng: 31.446871}
    });
}
function drop() {
    clearMarker();
    for (var i = 0; i < neighborhoods.length; i++) {
      addMarkerWithTimeout(neighborhoods[i], i * 200);  
    }
}
function addMarkerWithTimeout(position) {
    var singleMarker = new google.maps.Marker({
        position: position,
        map: map,
        animation: google.maps.Animation.DROP
    });
    singleMarker.addListener('click',function(){
        map.setZoom(15);
    })
    marker.push(singleMarker);
};
function clearMarker() {
    for (var i = 0; i < marker.length; i++) {
      marker[i].setMap(null);
    }
    marker = [];
};

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