JSFiddle - React, Tailwind, and code Playground

by David Kyle

HTML

<label for="address">Enter address</label>
<input type="text" name="address" id="address" />
<button type="button" name="search-button" onclick="doSearch()">
  Map
</button>
<div id='map' style='width: 400px; height: 300px;'></div>

JavaScript

mapboxgl.accessToken = 'pk.eyJ1IjoieGRhZXZheCIsImEiOiJjbGVkOHV1bXQwM3lmNDRzMml4czd6aW01In0.EeV24uX8ewolyHTaxqSOLg';
const mapboxClient = mapboxSdk({
  accessToken: mapboxgl.accessToken
});

function doSearch() {
  let address = document.getElementById('address').value;

  if (address && address.length > 0) {
    mapboxClient.geocoding
      .forwardGeocode({
        query: document.getElementById('address').value,
        autocomplete: false,
        limit: 1
      })
      .send()
      .then((response) => {
        if (
          !response ||
          !response.body ||
          !response.body.features ||
          !response.body.features.length
        ) {
          console.error('Invalid response:');
          console.error(response);
          return;
        }
        const feature = response.body.features[0];

        const map = new mapboxgl.Map({
          container: 'map',
          // Choose from Mapbox's core styles, or make your own style with Mapbox Studio
          style: 'mapbox://styles/mapbox/streets-v12',
          center: feature.center,
          zoom: 10
        });

        // Create a marker and add it to the map.
        new mapboxgl.Marker().setLngLat(feature.center).addTo(map);
      });
  } else {
    alert('no address provided.');
  }
}