Mapbox – How to Set Center on Mapbox GL Map

apihtml5javascriptmapboxmapbox-gl-js

I have a form HTML, e.g. like this:

<form id="form" method="post" action="#">
        <input class="sidebar__input" type="text" name="lat" id="latitude" />
        <input class="sidebar__input" type="text" name="lng" id="longitude"/>

        <input type="submit" id="button" value="Submit" onclick="onLoadConfigPress(document.getElementById('button').value)" />
</form>

Now, I want to pass latitude and longitude value to the center option in Map object:

var map=mapboxgl.Map({
   container: 'map',
   style: 'mapbox://styles/mapbox/streets-v9',
   center: [longit, latit],  <------ **HERE**
   ...

when I click on Submit button in HTML form.
What API Mapbox I must to use to pass latitude and longitude value to the center option? How to do?

Best Answer

When submitting your form, you can use your onLoadConfigPress function to read the values from the form fields and set the center of the map with setCenter:

For example:

// create map with initial center
var map = mapboxgl.Map({
   container: 'map',
   style: 'mapbox://styles/mapbox/streets-v9',
   center: [0, 0]
});

function onLoadConfigPress() {
  // get long and lat 
  var longitude = document.getElementById('longitude').value;
  var latitude = document.getElementById('latitude').value;

  // set center of map
  map.setCenter([longitude, latitude])
}

and call the function on submit

<form id="form">
  <input class="sidebar__input" type="text" name="lat" id="latitude" />
  <input class="sidebar__input" type="text" name="lng" id="longitude"/>
  <button type="button" onclick="onLoadConfigPress()">Set center</button>
</form>
Related Question