为不同类别创建标记,并希望为不同的地点类型设置不同的标记图标。
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: mapit,
position: place.geometry.location,
icon: "link-to-icon"
});
}
上述代码中可以包含哪些内容来测试该地点是否属于不同类型?
例如只有两种类型" night_club"和" cafe"我正在寻找这些方面的东西:
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: mapit,
position: place.geometry.location,
icon: "link-to-icon"
});
if (place.type == ['cafe']) {
marker.setIcon("link-to-cafe-icon]");
}
if (place.type == ['night_club']) {
marker.setIcon("link-to-night-club-icon]");
}
}
或者
function createMarker(place) {
var placeLoc = place.geometry.location;
if (place.type == ['cafe']) {
var marker = new google.maps.Marker({
map: mapit,
position: place.geometry.location,
icon: "link-to-cafe-icon"
});
}
if (place.type == ['night_club']) {
var marker = new google.maps.Marker({
map: mapit,
position: place.geometry.location,
icon: "link-to-night-club-icon"
});
}
}
place.type的语法是否正确?我没有在Google Maps API文档中看到类似的内容或place.getType,这是获取条件语句的地点类型的内容。
如何使条件工作并为不同地点类型的标记显示不同的图标?
答案 0 :(得分:1)
我建议这样
function createMarker(place) {
var myIcon;
var placeLoc = place.geometry.location;
switch (place.type) {
case 'cafe':
myIcon = "link-to-cafe-icon";
break;
case 'night_club':
myIcon = "link-to-night-club-icon";
break;
}
var marker = new google.maps.Marker({
map: mapit,
position: place.geometry.location,
icon: myIcon
});
}
答案 1 :(得分:1)
Places API会为每个结果返回types
数组,而不是type
。这是因为一个位置可以分配多个类型,例如["restaurant", "lodging"]
。这是supported types的列表。如果您使用"位置搜索"请参阅文档here。如果你使用"来电话或here呼叫。
因此,确定图标的代码必须比简单的开关更复杂。也许你可以在types
数组中观察某种类型的存在。这取决于你的需求,你必须自己决定,也许就像(使用jQuery库!):
function isInArray(a, b) {
return !!~a.indexOf(b)
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var placeIcon = "link-to-default-icon"; //some default icon, if you don't find a match
if(isInArray(place.types, "cafe")){
placeIcon = "link-to-cafe-icon";
}else if(isInArray(place.types, "night_club")){
placeIcon = "link-to-night-club-icon";
}//and so on for other icons
var marker = new google.maps.Marker({
map: mapit,
position: place.geometry.location,
icon: placeIcon
});
}