javaandy javaandy - 6 months ago 38
Javascript Question

How to test for Google Maps Place type with if conditional

Creating markers for different categories and want to have different marker icons for different place types.

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


What can be included in the above code to test whether the place is of different types?

For example with just two types "night_club" and "cafe" i'm going for something along these lines:

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


Or perhaps

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


What is the correct the syntax for place.type? i don't see anything like it or place.getType, something to get the place type for conditional statements, in the Google Maps API documentation.

How to make the conditionals work and display different icons for markers of different place types?

Answer

The Places API returns types array for each result, not type. This is because one location can have assigned multiple types like ["restaurant", "lodging"]. Here is the list of the supported types. See documentation here if you use "Places search" call or here if you use "Places details" call.

So your code to determine the icon will have to be more complicated than a simple switch. Maybe you can watch for an existence of a certain type in the types array. This depends on your needs, you will have to decide it yourself, maybe something like (with use of jQuery library!):

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