- Overview
- Geocoding Requests
- Geocoding Responses
- Reverse Geocoding
- Viewport Biasing
- Region Code Biasing
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.
The Google Maps API provides a geocoder class for geocoding and reverse geocoding dynamically from user input. When you first load the API, you will be allocated an initial quota of Geocoding requests. Once you have used this quota, additional requests will be rate-limited on a per-second basis. If instead you wish to geocode static, known addresses, see the Geocoding web service documentation.
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 via the
google.maps.Geocoder object. The Geocoder.geocode()
method initiates a request to the geocoding service, passing it a
GeocodeRequest object literal containing the input terms and a
callback method to execute upon receipt of the response.
The GeocodeRequest object literal contains the
following fields:
{
address: string,
location: LatLng,
bounds: LatLngBounds,
region: string
}
These fields are explained below.
address(required*) — The address which you want to geocode.latLng(required*) — TheLatLngfor which you wish to obtain the closest, human-readable address.bounds(optional) — TheLatLngBoundswithin which to bias geocode results more prominently. (For more information see Viewport Biasing below.)region(optional) — The region code, specified as a IANA languageregionsubtag. In most cases, these tags map directly to familiar ccTLD ("top-level domain") two-character values. (For more information see Region Code Biasing below.)componentRestrictions(optional) — Used to restrict results to a specific area. A filter consists of one or more of:route,locality,administrativeArea,postalCodeorcountry. Only the results that match all the filters will be returned. Filter values support the same methods of spelling correction and partial matching as other geocoding requests. See Component Filtering in the Geocoding web service for further details.
* Note: You may pass either an
address or a latLng to lookup. (If you pass a
latLng, the geocoder performs what is known as a reverse
geocode. See Reverse Geocoding for
more information.)
The bounds and region parameters will only
influence, not fully restrict, results from the geocoder.
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. Since
the Geocoder may return more than one entry, the GeocoderResults
object literal is an array.
Geocoding Results
The GeocoderResults object literal represents a single
Geocoding result and is an object of the following form:
results[]: {
types[]: string,
formatted_address: string,
address_components[]: {
short_name: string,
long_name: string,
postcode_localities[]: string,
types[]: string
},
partial_match: boolean,
geometry: {
location: LatLng,
location_type: GeocoderLocationType
viewport: LatLngBounds,
bounds: LatLngBounds
}
}
These fields are explained below:
types[]is an array indicating the type of the returned result. This array contains a set of zero or more tags identifying the type of feature returned in the result. For example, a geocode of "Chicago" returns "locality" which indicates that "Chicago" is a city, and also returns "political" which indicates it is a political entity.formatted_addressis a string containing the human-readable address of this location. Often this address is equivalent to the "postal address," which sometimes differs from country to country. (Note that some countries, such as Great Britain, do not allow distribution of true postal addresses due to licensing restrictions.) This address is generally composed of one or more address components. For example, the address "111 8th Avenue, New York, NY" contains separate address components for "111 8th Avenue" (a street address), "New York" (the city) and "NY" (the US state). These address components are noted below. (For more information on types, see Types below.address_components[]is an array containing the separate address components, as explained above.partial_matchindicates that the geocoder did not return an exact match for the original request, though it was able to match part of the requested address. You may wish to examine the original request for misspellings and/or an incomplete address.Partial matches most often occur when the requested street address does not exist in the specific locality. Partial matches may also be returned when a request matches two or more locations in the same locality. For example, "21 Henr St, Bristol, UK" will return a partial match for both Henry Street and Henrietta Street. Note that if a request includes a misspelled address component, the geocoding service may suggest an alternate address. Suggestions triggered in this way will not be marked as a partial match.
postcode_localities[]is an array denoting all the localities contained in a postal code. This is only present when the result is a postal code that contains multiple localities.geometrycontains the following information:locationcontains the geocoded latitude,longitude value. Note that we return this location as aLatLngobject, not as a formatted string.location_typestores additional data about the specified location. The following values are currently supported:google.maps.GeocoderLocationType.ROOFTOPindicates that the returned result reflects a precise geocode.google.maps.GeocoderLocationType.RANGE_INTERPOLATEDindicates that the returned result reflects an approximation (usually on a road) interpolated between two precise points (such as intersections). Interpolated results are generally returned when rooftop geocodes are unavailable for a street address.google.maps.GeocoderLocationType.GEOMETRIC_CENTERindicates that the returned result is the geometric center of a result such as a polyline (for example, a street) or polygon (region).google.maps.GeocoderLocationType.APPROXIMATEindicates that the returned result is approximate.
viewportstores the recommended viewport for the returned result.bounds(optionally returned) stores theLatLngBoundswhich can fully contain the returned result. Note that these bounds may not match the recommended viewport. (For example, San Francisco includes the Farallon Islands, which are technically part of the city, but should not be returned in the viewport.)
The addresses will be 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 Component Types
The types[] array within the returned result indicates the
address type. These types may also be returned within
address_components[] arrays to indicate the type of the
particular address component. Addresses within the geocoder may have multiple
types; the types may be considered "tags". For example, many cities are
tagged with the political and locality type.
The following types are supported and returned by the HTTP Geocoder:
street_addressindicates a precise street address.routeindicates a named route (such as "US 101").intersectionindicates a major intersection, usually of two major roads.politicalindicates a political entity. Usually, this type indicates a polygon of some civil administration.countryindicates the national political entity, and is typically the highest order type returned by the Geocoder.administrative_area_level_1indicates a first-order civil entity below the country level. Within the United States, these administrative levels are states. Not all nations exhibit these administrative levels.administrative_area_level_2indicates a second-order civil entity below the country level. Within the United States, these administrative levels are counties. Not all nations exhibit these administrative levels.administrative_area_level_3indicates a third-order civil entity below the country level. This type indicates a minor civil division. Not all nations exhibit these administrative levels.administrative_area_level_4indicates a fourth-order civil entity below the country level. This type indicates a minor civil division. Not all nations exhibit these administrative levels.administrative_area_level_5indicates a fifth-order civil entity below the country level. This type indicates a minor civil division. Not all nations exhibit these administrative levels.colloquial_areaindicates a commonly-used alternative name for the entity.localityindicates an incorporated city or town political entity.sublocalityindicates a first-order civil entity below a locality. For some locations may receive one of the additional types:sublocality_level_1through tosublocality_level_5. Each sublocality level is a civil entity. Larger numbers indicate a smaller geographic area.neighborhoodindicates a named neighborhood.premiseindicates a named location, usually a building or collection of buildings with a common namesubpremiseindicates a first-order entity below a named location, usually a singular building within a collection of buildings with a common name.postal_codeindicates a postal code as used to address postal mail within the country.natural_featureindicates a prominent natural feature.airportindicates an airport.parkindicates a named park.
An empty list of types indicates there are no known types for the particular address component, for instance Lieu-dit in France.
In addition to the above, address components may exhibit the following types:
post_boxindicates a specific postal box.street_numberindicates the precise street number.floorindicates the floor of a building address.roomindicates the room of a building address.
Status Codes
The status code may return one of the following values:
google.maps.GeocoderStatus.OKindicates that the geocode was successful.google.maps.GeocoderStatus.ZERO_RESULTSindicates that the geocode was successful but returned no results. This may occur if the geocode was passed a non-existentaddressor alatngin a remote location.google.maps.GeocoderStatus.OVER_QUERY_LIMITindicates that you are over your quota. Refer to the Usage limits exceeded article in the Google Maps API for Work documentation, which also applies to non-Business users, for more information.google.maps.GeocoderStatus.REQUEST_DENIEDindicates that your request was denied for some reason.google.maps.GeocoderStatus.INVALID_REQUESTgenerally indicates that the query (addressorlatLng) is missing.
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-canvas"), mapOptions);
}
function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.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);
}
});
}
<body onload="initialize()">
<div id="map-canvas" style="width: 320px; height: 480px;"></div>
<div>
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Encode" onclick="codeAddress()">
</div>
</body>
View example (geocoding-simple.html)
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.
The Geocoder supports reverse geocoding directly. Instead of
supplying a textual address, supply a comma-separated
latitude/longitude pair in the latLng 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. We return the second result, which is less specific than the first (in this case, a neighborhood name):
var geocoder;
var map;
var infowindow = new google.maps.InfoWindow();
var marker;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.730885,-73.997383);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
function codeLatLng() {
var input = document.getElementById("latlng").value;
var latlngStr = input.split(",",2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(11);
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
Note that in the previous example we showed the second result (by
selecting results[1]. The reverse geocoder often returns more
than one result. Geocoding "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.
The full list of addresses returned by the previous query are shown below.
results[0].formatted_address: "275-291 Bedford Ave, Brooklyn, NY 11211, USA", results[1].formatted_address: "Williamsburg, NY, USA", results[2].formatted_address: "New York 11211, USA", results[3].formatted_address: "Kings, New York, USA", results[4].formatted_address: "Brooklyn, New York, USA", results[5].formatted_address: "New York, New York, USA", results[6].formatted_address: "New York, USA", results[7].formatted_address: "United States"
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 wish to match a more general address,
you may wish 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.
View example (geocoding-reverse.html)
Viewport Biasing
You can also instruct the Geocoding Service to prefer results within a given
viewport (expressed as a bounding box). You do so by setting the
bounds parameter within the GeocodeRequest 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"
}
}
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"
}
}
Region Code Biasing
You can also 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 IANA language
region subtag. In most cases, these tags map directly to
familiar ccTLD ("top-level domain") two-character values such as "uk" in
"co.uk" for example. In some cases, the region tag also supports
ISO-3166-1 codes, which sometimes differ from ccTLD values ("GB" for "Great
Britain" for example).
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"]
}]
}
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"]
}]
}