Gnik
Gnik

Reputation: 7426

How can I set dynamic center point in Mapboxgl?

I am working Mapbox-gl.js (v0.38.0) Ionic3 & angular4. I want to set the dynamic center point. The latitude and longitude should be set based on the data in the real time data place's latitude and longitude.

If I set static center point hard-coded, when my real time data changes it will show the center as per the new markers. So I want to set the center point dynamically.

I tried the following following link, mapbox example I have added the real time data and marker. But how can I set the expected center point?

Actually my requirement: For eg: if the real time data has multiple markers in New York, by default the center point should be pointed to New york. Next time the data may change to Callifornia, that time it should point to California. Based on the markers my center point should be set.

Upvotes: 1

Views: 4945

Answers (2)

Aravind
Aravind

Reputation: 389

You can use the built-in GeolocateControl to find the location of the user and move the center of the map to that location, Check out this example.

You can use the watchPosition option to enable the tracking of the user's location.

MapBox is actively working to improve the location tracking part. You will have better control over this in the next version, Check out this link.

Upvotes: 1

Denis Tsoi
Denis Tsoi

Reputation: 10414

The following snippet is inspired from zoom-to-linestring example on mapbox-gl

As @Aravind mentions above, we use map.fitBounds, however, we have to determine the bounds, we have to reduce the array of features to determine the LngLatBounds.

Just make sure you loaded the feature data.

Example

let features = [feature, feature]  // ... array of features

// first coordinate in features
let co = features[0].geometry.coordinates;

// we want to determine the bounds for the features data
let bounds = features.reduce((bounds, feature) => {
  return bounds.extend(feature.geometry.coordinates);
}, new mapboxgl.LngLatBounds(co[0].lng, co[0].lat));

// set bounds according to features
map.fitBounds(bounds, {
  padding: 50,
  maxZoom: 14.15,
  duration: 2000
});

Upvotes: 4

Related Questions