Skip to content
Related Articles

Related Articles

Node.js | Mapbox Forward Geocoding API
  • Last Updated : 31 May, 2020

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:

  1. It is easy to get started and easy to use.
  2. It converts text into geographic coordinates.

Installation of request module:

  1. You can visit the link to Install Request module. You can install this package by using this command.
    npm install request
  2. After installing request module you can check your request version in command prompt using the command.
    npm version request
  3. Now go to Mapbox Offical website and create an account and get your API KEY.
  4. 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

Filename: index.js




const request = require('request');
var 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 {
  
            var longitude = response.body.features[0].center[0]
            var latitude = response.body.features[0].center[1]
            var location = response.body.features[0].place_name
  
            console.log("Latitude :", latitude);
            console.log("Longitude :", longitude);
            console.log("Location :", location);
        }
    })
}
  
var address = 'Indore'; // Sample data
  
// Function call
forwardGeocoding(address);

Steps to run the program:

  1. The project structure will look like this:
    project structure
  2. Make sure you have installed request module using following command:
    npm install request
  3. Run index.js file using below command:
    node index.js

    Output of above command

So this is how you can use the Mapbox forward geocoding API which converts text into geographic coordinates.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :