Getting Latitude and Longitude from Google Places search api using Javascript

Learn getting latitude and longitude from google places search api using javascript with practical examples, diagrams, and best practices. Covers javascript, google-maps development techniques with...

Extracting Latitude and Longitude from Google Places Search API with JavaScript

Hero image for Getting Latitude and Longitude from Google Places search api using Javascript

Learn how to integrate the Google Places Search API into your JavaScript applications to retrieve precise latitude and longitude coordinates for locations.

The Google Places Search API is a powerful tool for developers to find information about places, including businesses, points of interest, and geographic locations. A common requirement in many web and mobile applications is to obtain the exact latitude and longitude coordinates for a place identified through a user search. This article will guide you through the process of using JavaScript to query the Google Places Search API and extract these crucial geographical data points.

Prerequisites and Setup

Before you can start querying the Google Places API, you need to set up a Google Cloud Project, enable the necessary APIs, and obtain an API key. This key will authenticate your requests to Google's services.

  1. Google Cloud Project: Create a new project or select an existing one in the Google Cloud Console.
  2. Enable APIs: Ensure the 'Places API' and 'Maps JavaScript API' are enabled for your project. The Maps JavaScript API is often used in conjunction with Places for displaying results on a map.
  3. API Key: Generate an API key and restrict it to prevent unauthorized use. For client-side JavaScript, you'll typically restrict it by HTTP referrer (your domain).

Once you have your API key, you'll include the Google Maps JavaScript API library in your HTML, making sure to append your API key to the script URL.

<!DOCTYPE html>
<html>
<head>
    <title>Google Places Lat/Lng</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
        #map { height: 400px; width: 100%; }
    </style>
</head>
<body>
    <input id="pac-input" class="controls" type="text" placeholder="Enter a location">
    <div id="map"></div>
    <div id="info"></div>

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

Basic HTML structure to load Google Maps JavaScript API with Places library.

Implementing Place Search and Geocoding

The Google Maps JavaScript API provides the google.maps.places.AutocompleteService and google.maps.places.PlacesService classes, along with the google.maps.Geocoder service, which are essential for this task. The AutocompleteService helps users find places by providing predictive search results, while the PlacesService can fetch detailed information about a selected place. Alternatively, the Geocoder can convert a place name or address into coordinates.

flowchart TD
    A[User types in search box] --> B{AutocompleteService 'getPlacePredictions'}
    B --> C[Display predictions to user]
    C --> D{User selects a prediction}
    D --> E{PlacesService 'getDetails' or Geocoder 'geocode'}
    E --> F[Extract 'geometry.location.lat()' and 'geometry.location.lng()']
    F --> G[Use Lat/Lng in application]

Workflow for obtaining Latitude and Longitude from Google Places API.

Let's look at a common scenario: using an autocomplete input field to allow users to search for a location and then retrieving its coordinates.

// app.js
let map;
let service;
let infowindow;

function initMap() {
    const sydney = new google.maps.LatLng(-33.867, 151.195);

    infowindow = new google.maps.InfoWindow();
    map = new google.maps.Map(document.getElementById('map'), {
        center: sydney,
        zoom: 15
    });

    const input = document.getElementById('pac-input');
    const searchBox = new google.maps.places.SearchBox(input);

    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    // Bias the SearchBox results towards current map's viewport.
    map.addListener('bounds_changed', () => {
        searchBox.setBounds(map.getBounds());
    });

    let markers = [];
    // Listen for the event fired when the user selects a prediction and retrieve
    // more details for that place.
    searchBox.addListener('places_changed', () => {
        const places = searchBox.getPlaces();

        if (places.length == 0) {
            return;
        }

        // Clear out the old markers.
        markers.forEach((marker) => {
            marker.setMap(null);
        });
        markers = [];

        // For each place, get the icon, name and location.
        const bounds = new google.maps.LatLngBounds();

        places.forEach((place) => {
            if (!place.geometry || !place.geometry.location) {
                console.log("Returned place contains no geometry");
                return;
            }

            const lat = place.geometry.location.lat();
            const lng = place.geometry.location.lng();

            document.getElementById('info').innerHTML = `
                <p><strong>Place Name:</strong> ${place.name}</p>
                <p><strong>Latitude:</strong> ${lat}</p>
                <p><strong>Longitude:</strong> ${lng}</p>
            `;

            console.log(`Place: ${place.name}, Lat: ${lat}, Lng: ${lng}`);

            const icon = {
                url: place.icon,
                size: new google.maps.Size(71, 71),
                origin: new google.maps.Point(0, 0),
                anchor: new google.maps.Point(17, 34),
                scaledSize: new google.maps.Size(25, 25),
            };

            // Create a marker for each place.
            markers.push(
                new google.maps.Marker({
                    map,
                    icon,
                    title: place.name,
                    position: place.geometry.location,
                })
            );

            if (place.geometry.viewport) {
                // Only geocodes have viewport.
                bounds.union(place.geometry.viewport);
            } else {
                bounds.extend(place.geometry.location);
            }
        });
        map.fitBounds(bounds);
    });
}

JavaScript code for initializing the map, setting up a SearchBox, and extracting latitude/longitude.

Handling Geocoding for Addresses

If you have a specific address string and need its coordinates without an interactive search box, you can use the google.maps.Geocoder service directly. This is useful for batch processing or when an exact address is already known.

function geocodeAddress(geocoder, address) {
    geocoder.geocode({ 'address': address }, (results, status) => {
        if (status === 'OK') {
            if (results[0]) {
                const lat = results[0].geometry.location.lat();
                const lng = results[0].geometry.location.lng();
                console.log(`Address: ${address}, Lat: ${lat}, Lng: ${lng}`);
                // You can now use lat and lng in your application
            } else {
                console.log('No results found for address:', address);
            }
        } else {
            console.log('Geocoder failed due to:', status);
        }
    });
}

// Example usage:
// const geocoder = new google.maps.Geocoder();
// geocodeAddress(geocoder, '1600 Amphitheatre Parkway, Mountain View, CA');

Using the Geocoder service to convert an address string to latitude and longitude.