Node.js Mapbox Forward Geocoding API
Last Updated :
03 Apr, 2023
Forward Geocoding: Forward geocoding converts text into geographic coordinates. For example, turning ‘Indore’ into 22.7196, 75.8577. Mapbox is popular for Geocoding API and other locations and map services.
Feature of Mapbox Forward Geocoding API:
- It is easy to get started and easy to use.
- It converts text into geographic coordinates.
Installation of request module:
You can visit the link to the Install Request module. You can install this package by using this command.
npm install request
After installing the request module you can check your request version in the command prompt using the command.
npm version request
Now go to Mapbox Official website and create an account and get your API KEY.
After that, you can create a folder and add a file for example index.js, To run this file you need to run the following command.
node index.js
Project Structure:
Filename:
index.js
javascript
const request = require( 'request' );
let ACCESS_TOKEN = 'YOUR_API_KEY' ;
const forwardGeocoding = function (address) {
+ encodeURIComponent(address) + '.json?access_token='
+ ACCESS_TOKEN + '&limit=1' ;
request({ url: url, json: true }, function (error, response) {
if (error) {
callback( 'Unable to connect to Geocode API' , undefined);
} else if (response.body.features.length == 0) {
callback( 'Unable to find location. Try to '
+ 'search another location.' );
} else {
let longitude = response.body.features[0].center[0]
let latitude = response.body.features[0].center[1]
let location = response.body.features[0].place_name
console.log( "Latitude :" , latitude);
console.log( "Longitude :" , longitude);
console.log( "Location :" , location);
}
})
}
let address = 'Indore' ;
forwardGeocoding(address);
|
Steps to run the program:
Make sure you have installed the request module using the following command:
npm install request
Run the index.js file using the below command:
node index.js
So this is how you can use the Mapbox forward geocoding API which converts text into geographic coordinates.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...