1

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.

4

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]});
|improve this answer|||||
0

Your getURLParameter function is returning a String like "-84.83762741088867,43.179770125276974", but map.setCenter needs a LngLatLike ie. something like this.

var v1 = new mapboxgl.LngLat(-122.420679, 37.772537);
var v2 = [-122.420679, 37.772537];

You can use the split function to get an array assuming your location param is expecting lng,lat. If lat,lng then you'll need to swap the order before passing the array to setCenter.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.