我有一个谷歌地图应用程序,它从数据库中提取标记信息并将其写入 json 文件。 googlemaps 加载 json 并创建点等。我有一个自定义图标的选项,具体取决于 json 类型字段。如果用户输入不同的类型或在字段中放置空格,则会破坏 map 。
我想设置一个默认标记图标来处理数据库中不在 javascript 选择器中的空格和新类型。理想情况下是通配符或默认图标。我可以用mysql trim 空格并限制提交表单中的输入类型。在 googlemap js 中应用它似乎更灵活。它将允许新类型,而无需对自定义图标进行编码。
我来自谷歌地图 api 的 javascript 代码:
// set the base url for icons
var iconBase = '/kml/icons/';
var icons = {
Camping: {
icon: iconBase + 'camping.png'
},
Access: {
icon: iconBase + 'boat-ramp.png'
},
Showers: {
icon: iconBase + 'shower.png'
}
/* to deal with spaces and types not included above *
%wildcard%: {
icon: iconBase + 'red.png'
}
*/
};
json看起来像这样:
var siteData =[
{
"id":"13",
"name":"Banks",
"river":"Payette",
"type":"Access",
"lat":"44.085070",
"lng":"-116.115750"
},
{
"id":"57",
"name":"Slides",
"river":"Pack River",
"type":"Camping ",
"lat":"48.127099",
"lng":"-116.604248"
},
{
"id":"58",
"name":"Cold Springs",
"river":"Payette",
"type":"",
"lat":"48.127099",
"lng":"-116.604248"
},
第二个和第三个实例,第二个有一个空格,第三个在类型字段中是空白的。那些会破坏 map 。
最佳答案
没有定义默认值的方法,而 object["somePropertyName"] 未由天真的 javascript 定义。
到目前为止,javascript 也不支持使用正则表达式作为属性名。
(或者也许有 是 但我不知道。)
我猜属性:google.maps.Marker 的图标是数据类型与图标不匹配时破坏 map 的原因。
google map api 文档示例代码:
var marker = new google.maps.Marker({
position: feature.position,
icon: icons[feature.type].icon,
map: map
});
在您的情况下,当数据类型为“Camping”或“”时,icons[feature.type] 未定义。而且 icons[feature.type].icon (= undefined.icon) 会破坏 map 。
如果我猜到了,你可以改变你的 google.maps.Marker 如下:
var marker = new google.maps.Marker({
position: feature.position,
icon:icons[feature.type] ? icons[feature.type].icon : '',
map: map
});
或者
var marker = new google.maps.Marker({
position: feature.position,
icon:function(){
/* some conditions*/
}(),
map: map
});
关于javascript - 谷歌地图自定义标记设置默认图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48994161/