[GIS] Using a variable for map.setcenter in mapbox gl js

javascriptmapbox-gl-js

I'm trying to set the center of my map using coordinates passed into the page via the url. I can retrieve the coords, but but get this error when I try to use them:

Uncaught Error: LngLatLike argument must be specified as a LngLat instance, an object {lng: , lat: }, or an array of [, ]

I get the coords like this

function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + 
'=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
var center =getURLParameter('location');

open my map with

    mapboxgl.accessToken = 'pk.eyJ1IjoidHJveWIiLCJhIjoiY2pkb3F0cmJnMHA0YTJ4cXB3Mjc0Y3g0eCJ9.3Myq7AzC4yxR8hi9Ubchdw';
    var map = new mapboxgl.Map({
        container: 'map',
        style: 'mapbox://styles/mapbox/streets-v9',
        center: [-88.75, 42.15],
        zoom: 8
    });

and load my layers and set the center of my map in

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

map.setCenter(center);

my url looks like this:
http://mywebsite.com/Map.html?location=-84.83762741088867,43.179770125276974&name=otherdata

I can get the name value and use it to specify my map layer.

Best Answer

Step 1:

Your method getURLParameter("location") returns latitude,longitude values as string "-84.83762741088867,43.179770125276974"

Step 2:

Store returned values in a variable

//It will return string

var center = getURLParameter("location");

//It will return an array ["latitude","longitude"]

var latLng = center.split(","); 

//convert the first element of the array to float num

var lat = parseFloat(latLng[0]);

//convert the second element of the array to float num

var lng = parseFloat(latLng[1]); 

Step 3:

Pass converted latitude and longitude values directly to Mapbox GL to center your map.

mapboxgl.accessToken = 'pk.eyJ1IjoiZmFyaGF0YWJiYXMiLCJhIjoiY2plODE2NGgxMDRhdjMzcGV6a3QxaGE4OSJ9.O7Gu6jLiZe2y_gPK6AZJyA';
var map = new mapboxgl.Map({
    container: 'map', // container id
    style: 'mapbox://styles/mapbox/streets-v9', // stylesheet location
    center: [lng, lat], // starting position [lng, lat]
    zoom: 9 // starting zoom
});

or use MapboxGL flyTo method

map.flyTo({center:[lng, lat]});