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
//It will return an array ["latitude","longitude"]
//convert the first element of the array to float num
//convert the second element of the array to float num
Step 3:
Pass converted latitude and longitude values directly to Mapbox GL to center your map.
or use MapboxGL flyTo method