Codementor Events

Custom Infobox Labels with Google Maps Places API

Published Oct 18, 2016Last updated Jan 18, 2017
Custom Infobox Labels with Google Maps Places API

Introduction

Many companies are interested in finding out how many of a certain business-type, competitor, supplier, or otherwise, might be in a particular area. Or maybe you're making an app and you only want users to see information about nearby parks.

If the area being searched is relatively small (one or two cities), the Google Places API is a great choice for querying businesses and other local locations. It is a bit complex to implement this in a lot of specific details, but getting started is a breeze.

Let's make a basic map that takes a set of latitude and longitude, and returns a set of simple nearby labels showing particular kinds of local places.

To see the finished map from this tutorial, click here.

Getting started

Here's all you need to get started:

  • A basic HTML editor
  • Live internet access to Google's API
  • Infobox.js

We'll be using:

  • Places JS API
  • Google Maps JS API
  • Infobox library
  • Basic CSS and HTML

Create a new folder and this simple directory:

- Google_Map_Infobox_Labels/
 - index.html
 - infobox.js

Let's get coding!

HTML setup

First of all, let's make a simple HTML page that will house our map along with the start of the map itself:

<!DOCTYPE html>
<html>
  <head>
    <title>Custom Label Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
    <script src="infobox.js"></script>
    <script>
      var map;
      function initMap() {
          // Map code will go here
      }
      initMap();
    </script>
  </body>
</html>

Vancouver's as good a place as any for our demo (that's where I live)! I also really love that Google Maps doesn't require any API key anymore making it much easier to deploy code quickly.

You can see we've attached the Places library (?libraries=places) on the end of our script call for Google Maps. This is required!

Removing default map styles and restyling

Optional step: you don't need to restyle the map, but it will help with the display.

In order to have our labels be more visible, we have to get rid of some of the noise on the map created by other labels. So, here's some useful code to remove various kinds of labels (administrative, geographic, road, etc).

Add this code (place it inside the initMap() function):

var myStyle = [{
  featureType: "administrative",
  elementType: "labels",
  stylers: [{
    visibility: "on"
  }]
}, {
  featureType: "water",
  elementType: "labels",
  stylers: [{
    visibility: "off"
  }]
}, {
  featureType: "road",
  elementType: "labels",
  stylers: [{
    visibility: "off"
  }]
}, {
  featureType: "poi",
  elementType: "labels",
  stylers: [{
    visibility: "off"
  }]
}];

map = new google.maps.Map(document.getElementById('map'), {
  center: {
    lat: 49.3268,
    lng: -122.9520
  },
  zoom: 15,
  mapTypeControlOptions: {
    mapTypeIds: ['mystyle', google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.TERRAIN]
  },
  mapTypeId: 'mystyle'
});
map.mapTypes.set('mystyle', new google.maps.StyledMapType(myStyle, {
  name: 'My Style'
}));

This creates a custom layer, like the Roadmap or Satellite map, that the user can switch to, allowing for labels to be removed. This is a neat trick to have in your toolbox!

Querying the Places API for custom locations

The Places API is great for returning all nearby locations, but what if we want to get back something more specific?

Here, I'm telling the Places API that I want all parks, and only parks. But you can check out the Places types list and get all kinds of different searches going!

var request = {
  location: {
    lat: 49.3268,
    lng: -122.9520
  },
  radius: '3000',
  type: ['park']
};

var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, function(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      console.log(results[i]);
      // Will place infobox creation code here
    }
  }
});

Here, we're setting up our query by giving it a center point — our location — and a radius (in meters), as well as the type.

Then we use the PlacesService to shoot off a search and get back results, and console log out the resulting places in a for loop.

Setting up Infobox labels

Now, let's get the labels showing! Instead of markers, as what might be done normally, we're making labels instead. To do this, we'll use the infobox class from the infobox.js library as follows. Please note that this goes into the for loop from the code example above.

var place = results[i];
var labelText = results[i].name;
var myOptions = {
  content: labelText,
  maxWidth: "200px",
  boxStyle: {
    border: "none",
    textAlign: "center",
    fontSize: "12pt",
    background: "white",
    opacity: "0.7",
    padding: "1px"
  },
  disableAutoPan: true,
  pixelOffset: new google.maps.Size(0, -10),
  position: place.geometry.location,
  closeBoxURL: "",
  isHidden: false,
  pane: "mapPane",
  enableEventPropagation: true
};

var ibLabel = new InfoBox(myOptions);
ibLabel.open(map);

You can see fairly clearly where the settings are going—you can change the opacity, background, font size, and more from here.

Possible improvements

That's it! With that simple code, you now have a basic label map that you can customize in all sorts of more complex ways. Here's some ideas that could make it even better:

  • Adding a central marker to know the starting location
  • A visible circle for the radius search
  • Searching multiple types of places at the same time
  • Improving the styling of the labels to have them "pop" more
  • Adding checkboxes allowing users to search different types

To see the whole final map from this tutorial, click here.

There's a whole world of maps out there for you to explore! Thanks for reading, and good luck!

Discover and read more posts from Victor Gerard Temprano
get started
post comments1Reply
xgqfrms
8 years ago

Google Maps Places API