javascript - 谷歌地图自定义标记设置默认图标

标签 javascript google-maps-api-3 error-handling google-maps-markers

我有一个谷歌地图应用程序,它从数据库中提取标记信息并将其写入 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/

相关文章:

android - 需要有关 Google Map API 自动完成教程的帮助

flask - 发生错误时显示主页

error-handling - 通过依赖关系管理多个Pod的健康状况

ember.js - 使用 Ember 保存不成功时显示错误

javascript - 将元素添加到 dom 并使用 jquery 应用类不应用 css3 转换

javascript - 更优雅的方式来获得过滤值(value)?

javascript - 用户在 Javascript 中输入后如何存储总分?

javascript - 将多个参数传递给 page.evaluate()

javascript - 无法通过传递经纬度数组来设置折线的路径

google-maps - 通过 HTTPS 的 Google Maps API v3?