-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmapbox-geocoder-utils.js
More file actions
54 lines (49 loc) · 2.01 KB
/
mapbox-geocoder-utils.js
File metadata and controls
54 lines (49 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"use strict";
/***
* geocode is a method to search for coordinates based on a physical address and return
* @param {string} search is the address to search for the geocoded coordinates
* @param {string} token is your API token for MapBox
* @returns {Promise} a promise containing the latitude and longitude as a two element array
*
* EXAMPLE:
*
* geocode("San Antonio", API_TOKEN_HERE).then(function(results) {
* // do something with results
* })
*
*/
function geocode(search, token) {
// api url
var baseUrl = 'https://api.mapbox.com';
// the enpoint when i request lgn and lat based on location name
var endPoint = '/geocoding/v5/mapbox.places/';
// this fetch request takes in a url endpoint that will return the lgn, lat
return fetch(`${baseUrl}${endPoint}${encodeURIComponent(search)}.json?access_token=${token}`)
.then( res => res.json() )
// to get all the data from the request, comment out the following three lines...
.then( data => {
console.log(data)
return data.features[0].center
});
}
/***
* reverseGeocode is a method to search for a physical address based on inputted coordinates
* @param {object} coordinates is an object with properties "lat" and "lng" for latitude and longitude
* @param {string} token is your API token for MapBox
* @returns {Promise} a promise containing the string of the closest matching location to the coordinates provided
*
* EXAMPLE:
*
* reverseGeocode({lat: 32.77, lng: -96.79}, API_TOKEN_HERE).then(function(results) {
* // do something with results
* })
*
*/
function reverseGeocode(coordinates, token) {
let baseUrl = 'https://api.mapbox.com';
let endPoint = '/geocoding/v5/mapbox.places/';
return fetch(`${baseUrl}${endPoint}${coordinates.lng},${coordinates.lat}.json?access_token=${token}`)
.then( res => res.json() )
// to get all the data from the request, comment out the following three lines...
.then( data => data.features[0].place_name );
}