javascript - 带有 Google Places 库的 Google Maps 中不同地点类型的不同图像

标签 javascript google-maps google-maps-markers google-places

我是 javascript 的新手,无法弄清楚使用谷歌地图中的地点库为不同类型地点的结果使用不同自定义图标的逻辑。 例如 - 这将请求体育场馆和公园

var request = {
      location: myLatLng,
      radius: 20000,
      types: ['stadium','park']
    };
    infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);
    service.search(request, callback);

回调函数包括创建标记函数

function callback(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
        createMarker(results[i]); 
      } 
    }
}

创建标记函数如下所示

var emu = 'EMU_test_icon.png'

function createMarker(place) {
    var placeLoc = place.geometry.location;
    var marker = new google.maps.Marker({
      map: map,
      icon: emu,
      position: place.geometry.location
    }); 

所以我知道如何分配所有标记以使用 EMU_test_icon 图像,但我如何将“体育场”地点类型的结果定向到我列出的图标 (emu) 但为“公园”的结果创建标记到不同的自定义图标 (image2)?

最佳答案

传递给 createMarker 方法的“place”参数有一个可以提供帮助的“type”属性。请参阅引用资料 here在 PlaceSearchResults 标题下。

您可以将这两个图标存储在 map 中,并根据地点类型查找图标类型。

// store the icons in a map, key'd by type
var iconMap = {'stadium': 'EMU_test_stadium_icon.png', 'park': 'EMU_test_park_icon.png'};

// access types array from PlaceResult object
//  search to find the string "stadium" and "park"
//  default the type to stadium and check to see if place is a park
//  if its a park update the type of icon we select
//  in the original call to create a marker, get the icon string by type
function createMarker(place) {

    var placeLoc = place.geometry.location,
        isStadium = place.types.indexOf("stadium") !== -1,
        isPark = place.types.indexOf("park") !== -1,
        iconType = "stadium";

    if (isPark) {
        iconType = "park";
    }

    new google.maps.Marker({
        map: map,
        icon: iconMap[iconType],
        position: place.geometry.location
    });

}  

*注意:这在 IE < 9 中不起作用(不向数组原型(prototype)添加 indexOf 函数)

*注意 2:假设您的“ map ”变量在别处声明

关于javascript - 带有 Google Places 库的 Google Maps 中不同地点类型的不同图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11511757/

相关文章:

google-maps - 如何使用 Google map 显示国家边界、美国州边界和城市边界?

javascript - 谷歌地图 - 获取标记的位置

javascript - Google Chrome 无法显示个人 map

javascript - 使用 if 语句检查变量 true

javascript - 我不明白为什么我们应该包括 var result=false 和 result=true

java - 谷歌地图标记showinfowindow自定义Android

javascript - 谷歌地图 : How to add HTML elements to specific coordinates?

javascript - 在禁用橡皮筋效果的页面中检测滚动方向

javascript - 如何显示用 JavaScript 创建的 Canvas ?

javascript - 在谷歌地图上适合标记