1
votes

I have mapbox setup with geocoding so that a user can type in the 'Search' box, and once a location is selected, a marker is dropped at that location. I would like a marker to already be dropped on the map and a search term to already be entered into the Search box at the time of page load (I have a setup where a user selects a location, and if they go back to edit the page I want them to be able to see the location they had previously selected). Is this possible?

My code for initializing is:

    initMap(lat, lng) {
      const mapboxgl = require('mapbox-gl/dist/mapbox-gl.js')
      mapboxgl.accessToken =
        'access_token'
      const map = new mapboxgl.Map({
        container: 'map',
        style: 'mapbox://styles/mapbox/streets-v11?optimize=true',
        center: [lat, lng],
        zoom: 8,
        attributionControl: false,
      })
      const geocoder = new MapboxGeocoder({
        accessToken: mapboxgl.accessToken,
        mapboxgl: mapboxgl,
      })
      map.addControl(geocoder)
      map.on('load', () => {
        geocoder.on('result', (result) => {
          const inputResult = result.result
          const coordinates = inputResult.geometry.coordinates
          const placeName = inputResult.place_name
          const lng = coordinates[0]
          const lat = coordinates[1]
          this.location = placeName
          this.latLng = [lat, lng]
        })
      })
    },
1

1 Answers

1
votes

You can specify a query which is already displayed in the search input box and for which a marker is automatically added to the map by using MapboxGeocoder#query in conjunction with Map#on and the 'load' event. For example, the following code displays text in the input field and a marker for "High Park" on map load:

var map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/streets-v11',
  center: [-79.4512, 43.6568],
  zoom: 13
});

var geocoder = new MapboxGeocoder({
  accessToken: mapboxgl.accessToken,
  mapboxgl: mapboxgl
});

map.addControl(geocoder);

map.on('load', () => {
  geocoder.query('High Park');    
});