Geocoding Service (original) (raw)

Skip to main content

Geocoding Service

Stay organized with collections Save and categorize content based on your preferences.

Note: Server-side libraries

Overview

Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway, Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can use to place markers or position the map.

Reverse geocoding is the process of converting geographic coordinates into a human-readable address (see Reverse geocoding (Address Lookup)).

You can also use the geocoder to find the address for a given place ID.

The Maps JavaScript API provides aGeocoder class for geocoding and reverse geocoding dynamically from user input. If instead you want to geocode static, known addresses, see theGeocoding web service.

Get started

Before using the Geocoding service in the Maps JavaScript API, first ensure that the Geocoding API is enabled in the Google Cloud console, in the same project you set up for the Maps JavaScript API.

To view your list of enabled APIs:

  1. Go to theGoogle Cloud console.
  2. Click the Select a project button, then select the same project you set up for the Maps JavaScript API and click Open.
  3. From the list of APIs on the Dashboard, look forGeocoding API.
  4. If you see the API in the list, you're all set. If the API is not listed, enable it:
    1. At the top of the page, select ENABLE API to display theLibrary tab. Alternatively, from the left side menu, select Library.
    2. Search for Geocoding API, then select it from the results list.
    3. Select ENABLE. When the process finishes,Geocoding API appears in the list of APIs on theDashboard.

Pricing and policies

Pricing

To learn about pricing and usage policies for the JavaScript Geocoding service, seeUsage and Billingfor the Geocoding API.

Policies

Your use of the Geocoding service must be in accordance with thePolicies for Geocoding API.

Geocoding Requests

Accessing the Geocoding service is asynchronous, since the Google Maps API needs to make a call to an external server. For that reason, you need to pass a callback method to execute upon completion of the request. This callback method processes the result(s). Note that the geocoder may return more than one result.

You access the Google Maps API geocoding service within your code using thegoogle.maps.Geocoder constructor object. TheGeocoder.geocode() method initiates a request to the geocoding service, passing it a GeocoderRequest object literal containing the input terms and a callback method to execute upon receipt of the response.

The GeocoderRequest object literal contains the following fields:

{ address: string, location: LatLng, placeId: string, bounds: LatLngBounds, componentRestrictions: GeocoderComponentRestrictions, region: string }

Required parameters: You must supply one, and only one, of the following fields:

Optional parameters:

Geocoding Responses

The Geocoding service requires a callback method to execute upon retrieval of the geocoder's results. This callback should pass two parameters to hold the results and a status code, in that order.

Geocoding Results

The GeocoderResult object represents a single geocoding result. A geocode request may return multiple result objects:

results[]: { types[]: string, formatted_address: string, address_components[]: { short_name: string, long_name: string, postcode_localities[]: string, types[]: string }, partial_match: boolean, place_id: string, postcode_localities[]: string, geometry: { location: LatLng, location_type: GeocoderLocationType viewport: LatLngBounds, bounds: LatLngBounds } }

These fields are explained below:

Addresses are returned by the Geocoder using the browser's preferred language setting, or the language specified when loading the API JavaScript using the language parameter. (For more information, see Localization.)

Address Types and Address Component Types

The types[] array in theGeocoderResult indicates the_address type_. The types[] array may also be returned within aGeocoderAddressComponent to indicate the type of the particular address component. Addresses returned by the geocoder may have multiple types; the types may be considered tags. For example, many cities are tagged with the political andlocality type.

The following types are supported and returned by the geocoder in both the address types and address component types:

An empty list of types indicates there are no known types for the particular address component, for example, Lieu-dit in France.

In addition to the above, address components may include the types below.

Note: This list is not exhaustive, and is subject to change.

Status Codes

The status code may return one of the following values:

In this example, we geocode an address and place a marker at the returned latitude and longitude values. Note that the handler is passed as an anonymous function literal.

var geocoder; var map; function initialize() { geocoder = new google.maps.Geocoder(); var latlng = new google.maps.LatLng(-34.397, 150.644); var mapOptions = { zoom: 8, center: latlng } map = new google.maps.Map(document.getElementById('map'), mapOptions); }

function codeAddress() { var address = document.getElementById('address').value; geocoder.geocode( { 'address': address}, function(results, status) { if (status == 'OK') { map.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); } else { alert('Geocode was not successful for the following reason: ' + status); } }); }

View example.

Viewport Biasing

You can instruct the Geocoding Service to prefer results within a given viewport (expressed as a bounding box). You do so by setting thebounds parameter within the GeocoderRequest object literal to define the bounds of this viewport. Note that biasing only_prefers_ results within the bounds; if more relevant results exist outside of these bounds, they may be included.

For example, a geocode for "Winnetka" generally returns this suburb of Chicago:

{ "types":["locality","political"], "formatted_address":"Winnetka, IL, USA", "address_components":[{ "long_name":"Winnetka", "short_name":"Winnetka", "types":["locality","political"] },{ "long_name":"Illinois", "short_name":"IL", "types":["administrative_area_level_1","political"] },{ "long_name":"United States", "short_name":"US", "types":["country","political"] }], "geometry":{ "location":[ -87.7417070, 42.1083080], "location_type":"APPROXIMATE" }, "place_id": "ChIJW8Va5TnED4gRY91Ng47qy3Q" }

However, specifying a bounds parameter defining a bounding box for the San Fernando Valley of Los Angeles results in this geocode returning the neighborhood named "Winnetka" in that location:

{ "types":["sublocality","political"], "formatted_address":"Winnetka, California, USA", "address_components":[{ "long_name":"Winnetka", "short_name":"Winnetka", "types":["sublocality","political"] },{ "long_name":"Los Angeles", "short_name":"Los Angeles", "types":["administrative_area_level_3","political"] },{ "long_name":"Los Angeles", "short_name":"Los Angeles", "types":["administrative_area_level_2","political"] },{ "long_name":"California", "short_name":"CA", "types":["administrative_area_level_1","political"] },{ "long_name":"United States", "short_name":"US", "types":["country","political"] }], "geometry":{ "location": [34.213171,-118.571022], "location_type":"APPROXIMATE" }, "place_id": "ChIJ0fd4S_KbwoAR2hRDrsr3HmQ" }

Region Code Biasing

You can set the Geocoding Service to return results biased to a particular region explicitly using the region parameter. This parameter takes a region code, specified as a two-character (non-numeric) Unicode region subtag. These tags map directly to familiar ccTLD ("top-level domain") two-character values such as "uk" in "co.uk" for example. In some cases, theregion tag also supports ISO-3166-1 codes, which sometimes differ from ccTLD values ("GB" for "Great Britain" for example).

When using the region parameter:

Geocoding requests can be sent for every domain in which the main Google Maps application offers geocoding. Note that biasing only prefers results for a specific domain; if more relevant results exist outside of this domain, they may be included.

For example, a geocode for "Toledo" returns this result, as the default domain for the Geocoding Service is set to the United States:

{ "types":["locality","political"], "formatted_address":"Toledo, OH, USA", "address_components":[{ "long_name":"Toledo", "short_name":"Toledo", "types":["locality","political"] },{ "long_name":"Ohio", "short_name":"OH", "types":["administrative_area_level_1","political"] },{ "long_name":"United States", "short_name":"US", "types":["country","political"] }], "place_id": "ChIJeU4e_C2HO4gRRcM6RZ_IPHw" }

A geocode for "Toledo" with the region field set to'es' (Spain) will return the Spanish city:

{ "types":["locality","political"], "formatted_address":"Toledo, España", "address_components":[{ "long_name":"Toledo", "short_name":"Toledo", "types":["locality","political"] },{ "long_name":"Toledo", "short_name":"TO", "types":["administrative_area_level_2","political"] },{ "long_name":"Castilla-La Mancha", "short_name":"CM", "types":["administrative_area_level_1","political"] },{ "long_name":"España", "short_name":"ES", "types":["country","political"] }], "place_id": "ChIJ8f21C60Lag0R_q11auhbf8Y" }

Component Filtering

You can set the Geocoding Service to return address results restricted to a specific area, by using a components filter. Specify the filter in the componentRestrictions parameter. Filter values support the same methods of spelling correction and partial matching as other geocoding requests.

The geocoder returns only the results that match all the component filters. That is, it evaluates the filter specifications as an AND, not an OR.

A components filter consists of one or more of the following items:

The following example demonstrates using the componentRestrictions parameter to filter bycountry and postalCode:

function codeAddress() { geocoder.geocode({ componentRestrictions: { country: 'AU', postalCode: '2000' } }, function(results, status) { if (status == 'OK') { map.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); } else { window.alert('Geocode was not successful for the following reason: ' + status); } }); }

Fulfill on Zero Results

For reverse geocoding, by default the promise is broken on status=ZERO_RESULTS. However, the additional response level fields of plus_code and address_descriptor may still be populated in this case. If true is provided for the fulfillOnZeroResults parameter, populated in this case. If true is provided for the fulfillOnZeroResults parameter, the promise is not broken and these additional fields are accessible from the promise if present.

The following is an example of this behavior for a latitude/longitude in Antarctica. Even though there are no reverse geocoding results, we can still print the plus code in the promise if we set fulfillOnZeroResults=true.

function addressDescriptorReverseGeocoding() {
  var latlng = new google.maps.LatLng(-75.290330, 38.653861);
  geocoder
    .geocode({
      'location': latlng,
      'fulfillOnZeroResults': true,
    })
    .then((response) => {
      console.log(response.plus_code);
    })
    .catch((error) => {
      window.alert(`Error`);
    });
}

Address Descriptors

Address descriptors include additional information that help describe a location using landmarks and areas. Check out the address descriptors demo to explore the feature.

Address descriptors can be enabled through the use of the extraComputations parameter. Include extra_computations=ADDRESS_DESCRIPTORS in a geocoding request , reverse geocoding request , or a places geocoding request to receive address descriptors in your response.

Example in places geocoding

The following query contains the address of a place in Delhi.

function addressDescriptorPlaceIdLookup() { geocoder.geocode({ geocoder.geocode({ 'placeId': 'ChIJyxAX8Bj9DDkRgBfAnBYa66Q', 'extraComputations': ['ADDRESS_DESCRIPTORS'] }, function(results, status) { if (status == 'OK') { console.log(results[0].address_descriptor); } else { window.alert('Geocode was not successful for the following reason: ' + status); } }); }

Example in reverse geocoding

The following query contains the latitude/longitude value for a location in Delhi.

function addressDescriptorReverseGeocoding() {
  var latlng = new google.maps.LatLng(28.640964,77.235875);
  geocoder
    .geocode({
      'location': latlng,
      'extraComputations': ["ADDRESS_DESCRIPTORS"],
    })
    .then((response) => {
      console.log(response.address_descriptor);
    })
    .catch((error) => {
      window.alert(`Error`);
    });
}

Address Descriptor Example

An example address_descriptor is as follows.

{ "address_descriptor" : { "areas" : [ { "containment" : "OUTSKIRTS", "display_name" : { "language_code" : "en", "text" : "Turkman Gate" }, "place_id" : "ChIJ_7LLvyb9DDkRMKKxP9YyXgs" }, { "containment" : "OUTSKIRTS", "display_name" : { "language_code" : "en", "text" : "Chandni Chowk" }, "place_id" : "ChIJWcXciBr9DDkRUb4dCDykTwI" }, { "containment" : "NEAR", "display_name" : { "language_code" : "en", "text" : "Katar Ganj" }, "place_id" : "ChIJH3cWUyH9DDkRaw-9CjvcRvY" } ], "landmarks" : [ { "display_name" : { "language_code" : "en", "text" : "Delite Cinema" }, "straight_line_distance_meters" : 29.9306755065918, "place_id" : "ChIJLfiYDCT9DDkROoEa7NdupUM", "travel_distance_meters" : 418.7794799804688, "spatial_relationship" : "ACROSS_THE_ROAD", "types" : [ "establishment", "movie_theater", "point_of_interest" ] }, { "display_name" : { "language_code" : "en", "text" : "YES Bank" }, "straight_line_distance_meters" : 66.83731079101562, "place_id" : "ChIJFYHM3yb9DDkRRKGkZl2mpSQ", "travel_distance_meters" : 489.0340270996094, "spatial_relationship" : "DOWN_THE_ROAD", "types" : [ "bank", "establishment", "finance", "point_of_interest" ] }, { "display_name" : { "language_code" : "en", "text" : "UCO Bank" }, "straight_line_distance_meters" : 25.38849639892578, "place_id" : "ChIJ-c6_wCb9DDkRjIk1LeqRtGM", "travel_distance_meters" : 403.2246398925781, "spatial_relationship" : "ACROSS_THE_ROAD", "types" : [ "atm", "bank", "establishment", "finance", "point_of_interest" ] }, { "display_name" : { "language_code" : "en", "text" : "Delhi By Cycle Meeting Point" }, "straight_line_distance_meters" : 44.02867126464844, "place_id" : "ChIJNxVfkSb9DDkRJD22l-eGFdM", "travel_distance_meters" : 97.41281890869141, "spatial_relationship" : "AROUND_THE_CORNER", "types" : [ "establishment", "point_of_interest", "tourist_attraction", "travel_agency" ] }, { "display_name" : { "language_code" : "en", "text" : "Axis Bank Branch" }, "straight_line_distance_meters" : 102.3495178222656, "place_id" : "ChIJr3uaDCT9DDkR8roHTVSn1x4", "travel_distance_meters" : 330.8566284179688, "spatial_relationship" : "DOWN_THE_ROAD", "types" : [ "bank", "establishment", "finance", "point_of_interest" ] } ] } }

There are two arrays in each address_descriptor object: landmarks andareas. The landmarks array contains up to 5 results ranked in order of relevance by taking account of proximity to the requested coordinate, the prevalence of the landmark and its visibility. Each landmark result contains the following values:

The areas object contains up to 3 responses and limits itself to places that represent small regions, such as neighborhoods, sublocalities, and large complexes. Areas that contain the requested coordinate are listed first and ordered from smallest to largest. Each areas result contains the following values:

Address Descriptor Coverage

Address descriptors are in GA for India. The use of address descriptors in India incurs no additional cost and usage is covered by the existingGeocoding (India) Essentials SKU.

Feedback

This feature is available in all regions. It is in GA for India and in the pre-GA Experimental launch stage for all other regions. We would appreciate feedback:

Reverse Geocoding (Address Lookup)

The term geocoding generally refers to translating a human-readable address into a location on a map. The process of doing the converse, translating a location on the map into a human-readable address, is known as_reverse geocoding_.

Instead of supplying a textual address, supply a comma-separated latitude/longitude pair in the location parameter.

The following example geocodes a latitude/longitude value and centers the map at that location, bringing up an info window with the formatted address:

TypeScript

function initMap(): void { const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 8, center: { lat: 40.731, lng: -73.997 }, } ); const geocoder = new google.maps.Geocoder(); const infowindow = new google.maps.InfoWindow();

(document.getElementById("submit") as HTMLElement).addEventListener( "click", () => { geocodeLatLng(geocoder, map, infowindow); } ); }

function geocodeLatLng( geocoder: google.maps.Geocoder, map: google.maps.Map, infowindow: google.maps.InfoWindow ) { const input = (document.getElementById("latlng") as HTMLInputElement).value; const latlngStr = input.split(",", 2); const latlng = { lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1]), };

geocoder .geocode({ location: latlng }) .then((response) => { if (response.results[0]) { map.setZoom(11);

    const marker = new google.maps.Marker({
      position: latlng,
      map: map,
    });

    infowindow.setContent(response.results[0].formatted_address);
    infowindow.open(map, marker);
  } else {
    window.alert("No results found");
  }
})
.catch((e) => window.alert("Geocoder failed due to: " + e));

}

declare global { interface Window { initMap: () => void; } } window.initMap = initMap;

JavaScript

function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 8, center: { lat: 40.731, lng: -73.997 }, }); const geocoder = new google.maps.Geocoder(); const infowindow = new google.maps.InfoWindow();

document.getElementById("submit").addEventListener("click", () => { geocodeLatLng(geocoder, map, infowindow); }); }

function geocodeLatLng(geocoder, map, infowindow) { const input = document.getElementById("latlng").value; const latlngStr = input.split(",", 2); const latlng = { lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1]), };

geocoder .geocode({ location: latlng }) .then((response) => { if (response.results[0]) { map.setZoom(11);

    const marker = new google.maps.Marker({
      position: latlng,
      map: map,
    });

    infowindow.setContent(response.results[0].formatted_address);
    infowindow.open(map, marker);
  } else {
    window.alert("No results found");
  }
})
.catch((e) => window.alert("Geocoder failed due to: " + e));

}

window.initMap = initMap;

View example

Try Sample

Note that in the previous example we showed the first result by selecting results[0]. The reverse geocoder often returns more than one result. Geocoded addresses are not just postal addresses, but any way to geographically name a location. For example, when geocoding a point in the city of Chicago, the geocoded point may be labeled as a street address, as the city (Chicago), as its state (Illinois) or as a country (The United States). All are addresses to the geocoder. The reverse geocoder returns all of these results.

The reverse geocoder matches political entities (countries, provinces, cities and neighborhoods), street addresses, and postal codes.

Here's an example of the list of addresses that the above query may return:

results[0].formatted_address: "277 Bedford Ave, Brooklyn, NY 11211, USA" results[1].formatted_address: "Grand St/Bedford Av, Brooklyn, NY 11211, USA" results[2].formatted_address: "Williamsburg, Brooklyn, NY, USA" results[3].formatted_address: "Brooklyn, NY, USA" results[4].formatted_address: "New York, NY, USA" results[5].formatted_address: "Brooklyn, NY 11211, USA" results[6].formatted_address: "Kings County, NY, USA" results[7].formatted_address: "New York-Northern New Jersey-Long Island, NY-NJ-PA, USA" results[8].formatted_address: "New York Metropolitan Area, USA" results[9].formatted_address: "New York, USA"

Addresses are returned in the order of best to least matches. Generally, the more exact address is the most prominent result, as it is in this case. Note that we return different types of addresses, from the most specific street address to less specific political entities such as neighborhoods, cities, counties, states, etc. If you want to match a more general address, you may want to inspect the results[].types field.

Note: Reverse geocoding is not an exact science. The geocoder will attempt to find the closest addressable location within a certain tolerance.

Retrieving an Address for a Place ID

Supply a placeId to find the address for a given place ID. The place ID is a unique identifier that can be used with other Google APIs. For example, you can supply the placeId returned by theRoads API to get the address for a snapped point. For more information about place IDs, see theplace ID overview.

When you supply a placeId, the request cannot contain any of the following fields:

The following example accepts a place ID, finds the corresponding address, and centers the map at that location. It also brings up an info window showing the formatted address of the relevant place:

TypeScript

// Initialize the map. function initMap(): void { const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 8, center: { lat: 40.72, lng: -73.96 }, } ); const geocoder = new google.maps.Geocoder(); const infowindow = new google.maps.InfoWindow();

(document.getElementById("submit") as HTMLElement).addEventListener( "click", () => { geocodePlaceId(geocoder, map, infowindow); } ); }

// This function is called when the user clicks the UI button requesting // a geocode of a place ID. function geocodePlaceId( geocoder: google.maps.Geocoder, map: google.maps.Map, infowindow: google.maps.InfoWindow ) { const placeId = (document.getElementById("place-id") as HTMLInputElement) .value;

geocoder .geocode({ placeId: placeId }) .then(({ results }) => { if (results[0]) { map.setZoom(11); map.setCenter(results[0].geometry.location);

    const marker = new google.maps.Marker({
      map,
      position: results[0].geometry.location,
    });

    infowindow.setContent(results[0].formatted_address);
    infowindow.open(map, marker);
  } else {
    window.alert("No results found");
  }
})
.catch((e) => window.alert("Geocoder failed due to: " + e));

}

declare global { interface Window { initMap: () => void; } } window.initMap = initMap;

JavaScript

// Initialize the map. function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 8, center: { lat: 40.72, lng: -73.96 }, }); const geocoder = new google.maps.Geocoder(); const infowindow = new google.maps.InfoWindow();

document.getElementById("submit").addEventListener("click", () => { geocodePlaceId(geocoder, map, infowindow); }); }

// This function is called when the user clicks the UI button requesting // a geocode of a place ID. function geocodePlaceId(geocoder, map, infowindow) { const placeId = document.getElementById("place-id").value;

geocoder .geocode({ placeId: placeId }) .then(({ results }) => { if (results[0]) { map.setZoom(11); map.setCenter(results[0].geometry.location);

    const marker = new google.maps.Marker({
      map,
      position: results[0].geometry.location,
    });

    infowindow.setContent(results[0].formatted_address);
    infowindow.open(map, marker);
  } else {
    window.alert("No results found");
  }
})
.catch((e) => window.alert("Geocoder failed due to: " + e));

}

window.initMap = initMap;

View example

Try Sample

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-05-01 UTC.