Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138221

How do I get the mapbox geocoding API and the isochrone API to work together?

$
0
0

After following these two tutorials on the mapbox website Isochrone API and Geocoding API I thought I would try to add the two together. I'd like the user to enter an address in the geocode search bar then plot the isochrone layer. My problem is the function getIso is firing before a location is entered and I'm returning this error

TypeError: geocoder.mapMarker is null

which I understand because there was no user input for the geocoding API to place a marker. You'll notice I'm grabbing the lat and lng from geocoder.

var lon = geocoder.mapMarker._lnglat.lng;
var lat = geocoder.mapMarker._lnglat.lat;

So how can I have my getIso function activate after a user enters information in geocoder?

    // // geocoder search bar
    var geocoder = new MapboxGeocoder({ 
        accessToken: mapboxgl.accessToken, 
        mapboxgl: mapboxgl,
        zoom: 13, 
        placeholder: "Enter an address or place name", 
        bbox: [-105.214, 40.451, -104.850, 40.841] 
      }, getIso());
    map.addControl(geocoder, 'top-left'); 
    console.log(geocoder)

    // // Create variables to use in isochrone API
    var urlBase = 'https://api.mapbox.com/isochrone/v1/mapbox/';
    var lon = geocoder.mapMarker._lnglat.lng;
    var lat = geocoder.mapMarker._lnglat.lat;
    var profile = 'cycling';
    var minutes = 10;

   // Create a function that sets up the Isochrone API query then makes an Ajax call
    function getIso() {
        var query = urlBase + profile + '/' + lon + ',' + lat + '?contours_minutes=' + minutes + '&polygons=true&access_token=' + mapboxgl.accessToken;

        $.ajax({
        method: 'GET',
        url: query
        }).done(function(data) {
            map.getSource('iso').setData(data);
        })
    };
    map.addSource('iso', {
        type: 'geojson',
        data: {
        'type': 'FeatureCollection',
        'features': []
        }
    });
    map.addLayer({
        'id': 'isoLayer',
        'type': 'fill',
        // Use "iso" as the data source for this layer
        'source': 'iso',
        'layout': {},
        'paint': {
        // The fill color for the layer is set to a light purple
        'fill-color': '#5a3fc0',
        'fill-opacity': 0.3
        }
    }, "poi-label");

Viewing all articles
Browse latest Browse all 138221

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>