Geocoding
The Geocode object is based on the Google maps geocoding API.
There are three things that you can do with the Geocode object, which is the same as the Google maps geocoding API.
- Convert an address into latitude and longitude coordinates.
- Reverse geocode, which converts latitude and longitude coordinates into an address.
- Find the address for a given Google maps place ID.
You can also restrict to a specific area, region, or latitude/longitude bounds.
Example usage
const geocoder = G.geocode({
address: '221 B Baker St, London, England'
});
geocoder.geocode()
.then((results) => {
console.log('Response: ', results);
})
.catch((error) => {
console.error('Error: ', error);
});
Here is an alternate call. This one doesn't pass options to the constructor. Instead the options are passed to the fetch method, which is an alias to the geocode method.
G.geocode().fetch({
address: '221 B Baker St, London, England'
}).then((results) => {
console.log('Response: ', results);
})
.catch((error) => {
console.error('Error: ', error);
});
Creating the Geocode object
G.geocode(options?: GeocodeValue): Geocode
There are a few ways to setup the Geocode
object.
Pass no value.
G.geocode(): Geocode
const geocoder = G.geocode();
geocoder.address = '221 B Baker St, London, England';
Pass a boolean value to disable the Zoom geocoder.
G.geocode(value: boolean): Geocode
Parameter | Type | Required | Description |
---|---|---|---|
value | boolean | Yes | Whether to enable the Zoom geocoder. |
If you pass a false
value to the geocode
method then that will disable and hide the Zoom geocoder when this is associated with a map.
const geocoder = G.geocode(false);
Pass an object of options.
G.geocode(options: GeocodeOptions): Geocode
Parameter | Type | Required | Description |
---|---|---|---|
options | GeocodeOptions | Yes | The configuration options. |
const geocode = G.geocode({
address: '221 B Baker St, London, England'
});
Pass an existing Geocode object.
G.geocode(value: Geocode): Geocode
Parameter | Type | Required | Description |
---|---|---|---|
value | Geocode | Yes | The existing Geocode object. |
const geocoder = G.geocode(existingGeocodeObject);
Geocode options
Type GeocodeOptions
.
GeocodeOptions is an object containing the configuration options for the Geocode object.
Option | Type | Default | Description |
---|---|---|---|
address | string | The address to geocode. | |
bounds | LatLngBoundsValue | The latitude/longitude bounds within which to search. | |
componentRestrictions | GeocodeComponentRestrictions | Used to restrict results to a specific area. | |
language | string | The language identifier in which the results should be returned. See the list of supported languages. | |
location | LatLngValue | The latitude/longitude value to do a reverse geocode lookup and get a human-friendly address with. | |
placeId | string | The Google maps place id to get a human-friendly address for. | |
region | string | The country code used to bias a search. It should be a two-character (non-numeric) Unicode region subtag or CLDR identifier. See the Country/region coverage for the list of region codes. |
Geocode component restrictions
Type GeocodeComponentRestrictions
These are the filters that resolve to a specific area. They set the Google Maps Geocoding Service to return address results restricted to a specific area. See Geocoding Component Filtering for more information.
Option | Type | Description |
---|---|---|
administrativeArea | string | Matches all the administrative_area levels. Optional. |
country | string | Matches a country name or a two letter ISO 3166-1 country code. Optional. |
locality | string | Matches against both locality and sublocality types. Optional. |
postalCode | string | Matches postal_code and postal_code_prefix. Optional. |
route | string | Matches the long or short name of a route. Optional. |
Properties
Property | Type | Description |
---|---|---|
address | string | The address to geocode. |
bounds | LatLngBoundsValue | The latitude/longitude bounds within which to search. |
componentRestrictions | GeocodeComponentRestrictions | Used to restrict results to a specific area. |
language | string | The language identifier in which the results should be returned. See the list of supported languages. |
location | LatLngValue | The latitude/longitude value to do a reverse geocode lookup and get a human-friendly address with. |
placeId | string | The Google maps place id to get a human-friendly address for. |
region | string | The country code used to bias a search. It should be a two-character (non-numeric) Unicode region subtag or CLDR identifier. See the Country/region coverage for the list of region codes. |
address
Get the address to geocode.
const address = geocode.address;
Set the address to geocode
geocode.address = '221 B Baker St, London, England';
bounds
Get the bounds within which to search.
const bounds = geocode.bounds;
Set the bounds.
geocode.bounds = [[51.533767, -0.1485557], [51.513767, -0.2085557]];
componentRestrictions
Get the component restrictions.
const componentRestrictions = geocode.componentRestrictions;
Set the component restrictions.
geocode.componentRestrictions = {country: 'US'};
language
Get the language.
const language = geocode.language;
Set the language.
geocode.language = 'fr';
location
Get the location.
const location = geocode.location;
Set the location.
geocode.location = {lat: '44.7', '-70.8'};
placeId
Get the placeId.
const placeId = geocode.placeId;
Set the placeId.
geocode.placeId = 'GhIJDcNHxJTSUsARn5Cdt7FTQ0A';
region
Get the region.
const region = geocode.region;
Set the region.
geocode.region = 'AT';
Making a geocode request
The geocoding request is asyncronous, which is why a promise is returned. You can use await to make the call or use try...catch to make the calls.
An error can be returned if invalid paramaters are passed or required parameters are missing.
You make the request by doing the following:
- Getting the Geocode object.
- Passing one of the required parameters.
- Using fetch or geocode to make the geocode request.
Using await
const geocoder = G.geocode({
address: '221 B Baker St, London, England'
});
(async () => {
try {
const result = await geocoder.fetch();
console.log('Result: ', result);
} catch (error) {
console.error('Error getting geocode: ', error);
}
})();
In the above example we make our own immediately invoked function so that an async call can be made with await
. You can do this differently within an async
method in your own code if you want.
Using try...catch
const geocoder = G.geocode({
address: '221 B Baker St, London, England'
});
geocoder.geocode()
.then((results) => {
console.log('Response: ', results);
})
.catch((error) => {
console.error('Error: ', error);
});
Setting parameters
You can set parameters in a few different ways. The examples below will set the address
parameter but you can use the different approaches to set any of the parameters.
Pass options to the constructor.
const geocode = G.geocode({
address: '221 B Baker St, London, England'
});
Set a property value.
const geocode = G.geocode();
geocode.address = '221 B Baker St, London, England';
Use a method to set a property value.
const geocode = G.geocode();
geocode.setAddress('221 B Baker St, London, England');
Pass the parameter to the fetch or geocode methods.
const geocode = G.geocode();
geocode.geocode({address: '221 B Baker St, London, England'});
// or
geocode.fetch({address: '221 B Baker St, London, England'});
Required parameters
When making a geocode request you must set one, and only one, of the following parameters:
- address - The address to geocode
- location - The LatLng to obtain the closest human-readable address. This is used for a reverse geocode request.
- placeId - The Google Maps place id to get the closest human-readable address.
When making the request the Geocode object will look for one of the above values in alphabetical order. The first one that is set will be used. If another of the required parameters is set then it will be ignored.
Geocode result
If the geocode request is successful then a GeocodeResults object is returned.
The GeocodeResults object holds the individual geocode result objects.
The Geocode object will always return GeocodeResults object for a successful response, even if no results are found.
Here is an example where the latitude and longitude are retrieved from an address.
G.geocode().setAddress('no match').fetch()
.then((response) => {
if (response.hasResults()) {
const result = response.getFirst();
const lat = result.getLatitude();
const lng = result.getLongitude();
} else {
console.log('no match was found');
}
});
Handling no results
The Google Maps geocoding API will return an ZERO_RESULTS
error if there are no matching results. This library will return an empty GeocodeResults object for the results value if there are no results.
You can test for if there are any matching results by using the GeocodeResults hasResults method.
let latitude;
let longitude;
G.geocode({address: '221 B Baker St, London, England'}).fetch()
.then((response) => {
if (response.hasResults()) {
// Do something
} else {
console.log('no match was found');
}
});
Request errors
An error can be thrown if the request is invalid, the request limits have been reached, the web page can't access the geocoder API, or an unknown error was returned.
The returned error will be a GeocoderErrorStatus value.
Here is an example with handling certain error types.
G.geocode().setAddress('1 main st, New York').fetch()
.then((results) => {
if (results.hasResults()) {
console.log('A match was found: ', results);
} else {
console.log('no match was found');
}
})
.catch((error) => {
if (error === G.GeocoderErrorStatus.ERROR) {
console.error('There was an error contacting Google.');
} else if (error === G.GeocoderErrorStatus.INVALID_REQUEST) {
console.error('The request was invalid.');
} else if (error === G.GeocoderErrorStatus.OVER_QUERY_LIMIT) {
console.error('The API query limit has been exceeded.');
} else if (error === G.GeocoderErrorStatus.REQUEST_DENIED) {
console.error('This site cannot use the Geocoder API.');
} else if (error === G.GeocoderErrorStatus.UNKNOWN_ERROR) {
console.error('There was an unknown error. Try again in a moment.');
}
});
Methods
fetch
fetch(options?: GeocodeOptions): Promise<GeocodeResult[]>
This calls the Google maps geocoder service to get the geocode value.
fetch
is an alias for geocode.
Parameter | Type | Required | Description |
---|---|---|---|
options | GeocodeOptions | The options for the geocode call. |
This return a GeocodeResult from the promise.
const geocoder = G.geocode({address: '221 B Baker St, London, England'});
geocoder.fetch()
.then((result) => {
console.log('result: ', result);
})
.catch((error) => {
console.log('Error: ', error);
});
You can also pass options to the geocode request. The options can be everything needed for the geocode request or additional options not already set.
const geocoder = G.geocode({address: '221 B Baker St, London, England'});
geocoder.fetch({language: 'fr', 'bounds': [[51.533767, -0.1485557], [51.513767, -0.2085557]]})
.then((result) => {
console.log('result: ', result);
})
.catch((error) => {
console.log('Error: ', error);
});
geocode
geocode(options?: GeocodeOptions): Promise<GeocodeResult[]>
This calls the Google maps geocoder service to get the geocode value.
You can also call fetch as it's an alias for geocode()
.
Parameter | Type | Required | Description |
---|---|---|---|
options | GeocodeOptions | The options for the geocode call. |
This return a GeocodeResult from the promise.
const geocoder = G.geocode({address: '221 B Baker St, London, England'});
geocoder.geocode()
.then((result) => {
console.log('result: ', result);
})
.catch((error) => {
console.log('Error: ', error);
});
You can also pass options to the geocode request. The options can be everything needed for the geocode request or additional options not already set.
const geocoder = G.geocode({address: '221 B Baker St, London, England'});
geocoder.geocode({language: 'fr', 'bounds': [[51.533767, -0.1485557], [51.513767, -0.2085557]]})
.then((result) => {
console.log('result: ', result);
})
.catch((error) => {
console.log('Error: ', error);
});
setAddress
setAddress(address: string): Geocode
Sets the address to geocode. This is an alternate method to setting the address property, passing the address
option to the geocode
object, or passing the address
to the fetch or geocode methods.
Parameter | Type | Required | Description |
---|---|---|---|
address | string | Yes | The address to geocode. |
geocoder.setAddress('221 B Baker St, London, England');
setBounds
setBounds(bounds: LatLngBoundsValue): Geocode
Set the bounds within which to bias geocode results more prominently. This is an alternate method to setting the bounds property, passing the bounds
option to the geocode
object, or passing the bounds
to the fetch or geocode methods.
Parameter | Type | Required | Description |
---|---|---|---|
address | LatLngBoundsValue | Yes | The latitude/longitude bounds within which to search. |
geocoder.setBounds({
sw: G.latLng(44, -68),
ne: G.latLng(44.7, -70.8),
});
setComponentRestrictions
setComponentRestrictions(componentRestrictions: GeocodeComponentRestrictions): Geocode
Set the component restrictions. This is an alternate method to setting the componentRestrictions property, passing the componentRestrictions
option to the geocode
object, or passing the componentRestrictions
to the fetch or geocode methods.
Parameter | Type | Required | Description |
---|---|---|---|
componentRestrictions | GeocodeComponentRestrictions | Yes | The component restrictions to set. |
geocoder.setComponentRestrictions({
country: 'US',
});
setLanguage
setLanguage(language: string): Geocode
Set the language for the response. This is an alternate method to setting the language property, passing the language
option to the geocode
object, or passing the language
to the fetch or geocode methods.
Parameter | Type | Required | Description |
---|---|---|---|
language | string | Yes | The language for the response. See the list of supported languages. |
geocoder.setLanguage('fr');
setLocation
setLocation(location: LatLngValue): Geocode
Set the location to reverse geocode. This is an alternate method to setting the location property, passing the location
option to the geocode
object, or passing the location
to the fetch or geocode methods.
Parameter | Type | Required | Description |
---|---|---|---|
location | LatLngValue | Yes | The latitude/longitude value to do a reverse geocode lookup and get a human-friendly address with. |
geocoder.setLocation({lat: '44.7', '-70.8'});
setPlaceId
setPlaceId(placeId: string): Geocode
Set the place id to geocode. This is an alternate method to setting the placeId property, passing the placeId
option to the geocode
object, or passing the placeId
to the fetch or geocode methods.
Parameter | Type | Required | Description |
---|---|---|---|
placeId | string | Yes | The Google maps place id to get a human-friendly address for. |
geocoder.setPlaceId('GhIJDcNHxJTSUsARn5Cdt7FTQ0A');
setRegion
setRegion(region: string): Geocode
Set the country code used to bias a search. This is an alternate method to setting the region property, passing the region
option to the geocode
object, or passing the region
to the fetch or geocode methods.
Parameter | Type | Required | Description |
---|---|---|---|
region | string | Yes | The country code used to bias a search. It should be a two-character (non-numeric) Unicode region subtag or CLDR identifier. See the Country/region coverage for the list of region codes. |
geocoder.setRegion('CL');
setOptions
setOptions(options: GeocodeOptions): Geocode
Set the options for the popup.
Parameter | Type | Required | Description |
---|---|---|---|
options | GeocodeOptions | Yes | The options for the popup. |
geocoder.setOptions({
address: '221 B Baker St, London, England',
language: 'es'
});