Mapbox JS SDK geocoding client undefined

Viewed 309

I'm trying to use the Mapbox JavaScript SDK to do forward geocoding from a VueJS app. I'm following along with this tutorial but can't figure out how to access the Mapbox client.

My imports:

import mapboxgl from 'mapbox-gl';
import mapboxSdk from '@mapbox/mapbox-sdk';

Then in mounted:

mapboxgl.accessToken = this.mapboxToken;
var mapboxClient = mapboxSdk({ accessToken: mapboxgl.accessToken });
this.map = new mapboxgl.Map({
     container: 'map',
     style: 'mapbox://styles/mapbox/streets-v11',
     center: [0, 0],
     zoom: 10
});
mapboxClient.geocoding.forwardGeocode({
    query: 'Wellington, New Zealand',
    autocomplete: false,
    limit: 1
})
    .send()
    .then(function(response) {
        if (
            response &&
            response.body &&
            response.body.features &&
            response.body.features.length
        ) {
            var feature = response.body.features[0];
            new mapboxgl.Marker().setLngLat(feature.center).addTo(this.map);
          }
    });

This produces a mapboxClient.geocoding is undefined error. I'm invoking the client the same way the tutorial is. Where am I going wrong?

1 Answers

I think you need to replace your import statement with this:

import mapboxSdk from '@mapbox/mapbox-sdk/services/geocoding'

That's based on my reading of the documentation.

To create a service client, import the service's factory function from '@mapbox/mapbox-sdk/services/{service}' and provide it with your access token.

Then you probably get rid of the .geocoding part too.

Presumably they package it like this so you don't have to bundle all the code for services you're not using - whereas by accessing it through unpkg you get everything.

Related