如何使用 if 条件测试 Google Maps Place 类型

How to test for Google Maps Place type with if conditional

正在为不同的类别创建标记,并希望为不同的地点类型设置不同的标记图标。

      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 地图 API 文档中,我没有看到类似的东西或 place.getType,用于获取条件语句的位置类型的东西。

如何使条件有效并为不同地点类型的标记显示不同的图标?

我建议这样

 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
      });

  }

每个结果的 Places API returns types 数组,而不是 type。这是因为一个位置可以分配多个类型,例如 ["restaurant", "lodging"]。如果您使用 "Places details" 调用,这里是 supported types. See documentation here if you use "Places search" call or 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
    });
  }