0

我使用自定義圖像作爲Google Map API的圖標/標記。我希望標記圖像在用戶放大地圖時調整大小。使用縮放調整自定義圖像標記大小 - Google Maps API v3

我採取了一些從這個問題的代碼:Google Maps :: Changing icon based on zoom level

不幸的是,這個腳本只改變了最後經/緯標記在我的名單。我不確定爲什麼,有誰能指出我的錯誤?

下面的代碼:

var locations = [ 
['Aaron Baddeley (130)',-25.274398,133.775136], 
['Adam Hadwin (176)',52.939916,-106.450864], 
['Adam Scott (7)',-26.65,153.066667], 
['Adilson da Silva (291)',-28.530554,30.895824], 
['Alejandro Canizares (167)',40.416775,-3.70379],]; 

var infowindow = new google.maps.InfoWindow({} 

var image = new google.maps.MarkerImage('images/marker11.gif', 
    new google.maps.Size(9,9), //size 
    null, //origin 
    null, //anchor 
    new google.maps.Size(9,9) //scale 
); 

var marker, i; 
for (i = 0; i < locations.length; i++) { 
    marker = new google.maps.Marker({ 
    position: new google.maps.LatLng(locations[i][1], locations[i][2]), 
    map: map, 
    icon: image, 
}); 

//when the map zoom changes, resize the icon based on the zoom level so the marker covers the same geographic area 
google.maps.event.addListener(map, 'zoom_changed', function() { 
    var pixelSizeAtZoom4 = 9; //the size of the icon at zoom level 4 
    var maxPixelSize = 350; //restricts the maximum size of the icon, otherwise the browser will choke at higher zoom levels trying to scale an image to millions of pixels 

    var zoom = map.getZoom(); 
    var relativePixelSize = Math.round(pixelSizeAtZoom4*Math.pow(1.2,zoom)); // use 2 to the power of current zoom to calculate relative pixel size. Base of exponent is 2 because relative size should double every time you zoom in 

    if(relativePixelSize > maxPixelSize) //restrict the maximum size of the icon 
    relativePixelSize = maxPixelSize; 

    if(zoom < 4) //when zooming < 4, fix pixel size to 9 
    relativePixelSize = 9; 


//change the size of the icon 

marker.setIcon(
    new google.maps.MarkerImage(
     marker.getIcon().url, //marker's same icon graphic 
     null,//size 
     null,//origin 
     null, //anchor 
     new google.maps.Size(relativePixelSize, relativePixelSize) //changes the scale 
    ) 
);   
}); 
+0

相關問題:[用縮放更改google地圖自定義圖標](http://stackoverflow.com/questions/18992074/change-google-maps-custom-icon-with-zoom) – geocodezip

回答

1

添加事件偵聽器,當你創建它們觸發標記的圖標的變化

map.addListener('zoom_changed', function() { 
    for (var i=0, len = locations.length; i < len; i++) { 
     // set new icon depending on the value of map.getZoom() 
     markers[i].setIcon(...) 
    } 
}); 

應保存您的標記在一個數組markerszoom_changed事件在for循環中,因此您可以將它們引用爲markers[i]

+0

感謝您的回覆!在創建數組時,我非常喜歡綠色,所以我嘗試使用不同的方法,基本上根據縮放級別調整相同的標記。 –

相關問題