我試圖給每個標記與不同的類別不同的標記圖像。 在JSON中,我有3個例子都有不同的類別(一,二和三)。谷歌地圖 - 每個類別的不同標記圖標
目前我有一個標記圖像被用於所有,但我想使用類別值來控制圖像的URL使用。
我可能正在考慮讓url變量插入類別顏色(var url =「http://domain.com/images/marker_」+ [category] +「.png」)。然後我可以將它與開關狀態混合在一起,但是就我而言。
對我來說,處理這個問題的最佳方法是什麼?
這裏是JS我有谷歌地圖。我正在使用API的v3。
(function() {
window.onload = function() {
// Creating a new map
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(30.033591,-36.035156),
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Creating the JSON data
var json = [
{
"title": "USA",
"lat": 37.616552,
"lng": -92.988281,
"description": "<strong>USA</strong> ...",
"category": "one"
},
{
"title": "France",
"lat": 48.372793,
"lng": 1.230469,
"description": "<strong>France</strong> ...",
"category": "two"
},
{
"title": "UK",
"lat": 51.517403,
"lng": -0.098877,
"description": "<strong>UK</strong> ...",
"category": "three"
}
]
// Custom marker - Need one for each category
var image = new google.maps.MarkerImage(
'http://i.imgur.com/3YJ8z.png',
new google.maps.Size(19,25), // size of the image
new google.maps.Point(0,0) // origin, in this case top-left corner
);
// Creating a global infoWindow object that will be reused by all markers
var infoWindow = new google.maps.InfoWindow();
// Marker Clusterer setup
var mcOptions = {
gridSize: 50,
maxZoom: 15
};
var markers = [];
// Looping through the JSON data
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title,
icon: image
});
markers.push(marker);
// Creating a closure to retain the correct data, notice how I pass the current data in the loop into the closure (marker, data)
(function(marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}// END for loop
// Cluster the markers
var markerCluster = new MarkerClusterer(map, markers, mcOptions);
}// END window.onload
})();
感謝
[這裏是邁克·威廉姆斯的經典類圖](http://www.geocodezip.com/v3_MW_example_categories.html )從他的v2教程(翻譯成v3)。解決您正在處理的問題。 – geocodezip
@geocodezip非常感謝。很好的發現。 – zizther