Integrating HTML5 geolocation with Google Maps JavaScript API

The combination of HTML5 geolocation with the Google Maps JavaScript APIs allows you to build dynamic web applications capable of detecting the user’s location and displaying nearby businesses. In this guide, we’ll go step by step through how to achieve this.

1. Getting the User’s Location with the Geolocation API

The Geolocation API is a native feature of modern browsers that allows you to obtain the user’s current position, with explicit permission. Here’s a basic example:

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
} else {
  alert("Geolocation not supported by this browser.");
}

function successCallback(position) {
  const latitude = position.coords.latitude;
  const longitude = position.coords.longitude;
  console.log("Latitude:", latitude, "Longitude:", longitude);
}

function errorCallback(error) {
  console.error("Geolocation error:", error);
}

2. Setting Up Google Maps with the JavaScript API

To use Google Maps APIs, you need to obtain an API key from Google Cloud Console and include the JavaScript file:

<script async defer
  src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap"></script>

The initMap function will be the entry point for creating and configuring the map.

3. Displaying the Map Centered on the User

Once the coordinates are obtained, you can create a map centered on the user’s location:

let map;

function initMap() {
  navigator.geolocation.getCurrentPosition(function(position) {
    const userLocation = {
      lat: position.coords.latitude,
      lng: position.coords.longitude
    };

    map = new google.maps.Map(document.getElementById("map"), {
      center: userLocation,
      zoom: 15
    });

    new google.maps.Marker({
      position: userLocation,
      map: map,
      title: "You are here"
    });

    findStores(userLocation);
  });
}

4. Searching for Nearby Businesses with the Places API

The Places Library allows you to perform nearby searches by specifying types of places, such as restaurants, cafes, bars, supermarkets, etc.

function findStores(location) {
  const service = new google.maps.places.PlacesService(map);

  const request = {
    location: location,
    radius: 1000, // in meters
    type: ["store"] // or ["restaurant", "cafe", "bar"]
  };

  service.nearbySearch(request, function(results, status) {
    if (status === google.maps.places.PlacesServiceStatus.OK) {
      for (let i = 0; i < results.length; i++) {
        const place = results[i];
        createMarker(place);
      }
    }
  });
}

function createMarker(place) {
  new google.maps.Marker({
    map: map,
    position: place.geometry.location,
    title: place.name
  });
}

5. Adding the Map Container

To display the map on your page, add an HTML element with a specific ID:

<div id="map" style="width: 100%; height: 500px;"></div>

6. Privacy and Performance Considerations

  • Always explicitly ask for user consent before accessing geolocation.
  • Avoid repeated geolocation requests; save the position once obtained.
  • Set timeouts or fallbacks in case the browser doesn’t respond.

Conclusions

The integration between the browser’s Geolocation API and Google Maps allows you to build interactive, location-aware experiences. Whether displaying shops, points of interest, or businesses, this combination of technologies provides great potential for enhancing the geographic relevance of your web content.

Back to top