fridayikon
fridayikon

Reputation: 25

Using Mapbox to specify coordinates for a business location

I'm sure this is a very simple thing, but how do I include the coordinates for a map using Mapbox? The product is a simple map embedded on a website with a marker at the store location. The business is in Ghana, West Africa. And the coordinates are [5.6513286, -0.1945831].

<script>
mapboxgl.accessToken = '';
var map = new mapboxgl.Map({
container: 'map',
center: [5.6513286, -0.1945831],
zoom: 5,
style: 'mapbox://styles/kopoku/ck826mkp719ne1iruuq8bpjmk'
});

var marker = new mapboxgl.Marker()
  .setLngLat([5.6513286, -0.1945831])
  .addTo(map);


</script>

Upvotes: 1

Views: 172

Answers (1)

Adriana Babakanian
Adriana Babakanian

Reputation: 1299

To achieve this, you'll need to add to the map a GeoJSON source containing the coordinate as a GeoJSON feature, and a symbol layer whose text-field property is set to a string containing the coordinates to be displayed using a get expression:

map.on('load', function() {

  map.addSource('point', {
    'type': 'geojson',
    'data': {    
      // feature for the coordinate to display
      'type': 'Feature',
      'geometry': {
        'type': 'Point',
        'coordinates': [-0.1945831, 5.6513286]
      },
      'properties': {
        'coordinates': '[-0.1945831, 5.6513286]',
      }
    }
  });

  map.addLayer({
    'id': 'point',
    'type': 'symbol',
    'source': 'point',
    'layout': {
      // get the coordinates from the source's "coordinates" property
      'text-field': ['get', 'coordinates'],
      'text-font': ['Open Sans Semibold', 'Arial Unicode MS Bold'],
    }
  });

});

Also, note that I switched the order of the center coordinates [5.6513286, -0.1945831] to [-0.1945831, 5.6513286] since the original point was located in the ocean rather than Ghana. This is indicative of the original latitude and longitude values being flipped.

Here is a JSFiddle with all the code: https://jsfiddle.net/yLz29m1g/. Please note that you'll need to add your own Mapbox access token where indicated in order to view the result. Here is a screenshot as a preview:

enter image description here

Upvotes: 1

Related Questions