How can I set dynamic center point in Mapboxgl? - mapbox

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.

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
});

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.

Related

How do you get all features within a bounding box regardless of zoom?

Given a bound box like the below picture, how do you get all the features contained within, regardless of if they are visible or not.
I have tried to get all roads using
let features = map.querySourceFeatures('composite', {sourceLayer: 'road'})
But it only gives me roads that are visible if I am zoomed in.
I have also tried
let features = map.queryRenderedFeatures([tile_info.swPt, tile_info.nePt])
But again, it only gets features visible on the map based on zoom level.
I need all the features within the bounding box regardless of what you can see or zoom level
It is in the nature of vector tiles that you can not do what you want to do here. You can only query data which has been loaded into the browser, and the point of the vector tile architecture is to prevent that happening at lower zooms.
You could consider a server based approach like Tilequery.

How to know if user's current location is within or near polyline?

I am making a location based tracking program where user can set his/her origin and destination point and then a polyline will be generated based on two coordinates. Now I want to know if user's current location is near or within polylines.
List<LatLng> coordinates is the coordinates that are used to draw polylines on Map.
Stream<LatLng> currentLocation is the stream that is listening to user's current location.
Never mind 😅
I found out there is a method on native google map PolyUtil isLocationOnPath() which return true if given point is within or near given List of coordinates.
I made a flutter plugin for that google_map_polyutil
First determine the value of "near" and you sould try to add or subtract this value to lat and long of the user and see if the new location has cross the line. (Signe of the addition or subtract has change).

How to convert pixels into the map coordinate when calling easeTo() in mapbox

I am developing an interactive map in HTML+JavaScript using mapboxgl (0.33.1). When the user clicks a button (which is associated with a particular location in the map), I call easeTo(), which put that location in the center of the map.
window.map.easeTo({
center: item.loc
});
Because my application has some overlapping UI over the bottom half of the map, I actually want to put that location not in the center of the map, but in the center of the top half of the map (25% from the top).
I'd appreciate if somebody could give me a hint how achieve it. My app knows the exact sizes of the window in Pixel (and also the zoom level), but (I assume) I need to convert it into the map-coordinate (from pixel) to add an appropriate offset to the "center" parameter I pass to easyTo() function.
I think I found the answer. I just need to call the project() method -- which was very hard to discover!

Leaflet - tooltips for overlapping polylines

Background:
I am working on a web based mapping application for hiking. So the map based on leaflet offers routes on hiking trails that are labeled. As any hiking trail can be part of multiple routes, routes - respectively the corresponding polylines representing the routes - can overlap.
Problem:
Each route has its tooltip (triggered by mouseover, {sticky:true}) showing its label which works as expected for non-overlapping polylines but as soon as two or more routes overlap only the polyline "on top" gets its tooltip opened. This behaviour is not bad per se but as all routes are equally important I would like to show all labels of the routes at the pointer's location (or something like a maximum of 5 labels + x more). I weren't able to find any issue related to this topic.
What I tried:
- Create a feature group for all routes, bind the tooltip to the group, hoping that the tooltip function provides an array of all polylines crossing the pointer's position. As it turned out, I only get information of the polyline on top
- I tried the same with a mousemove event on the map, no success
- Comparing pointer's layerPoint coordinates with all routes' _rings & _parts layPoint arrays to find matching layerPoints, but the success rate is only about 5% as these layerPoints only cover actual points of the polyline but not the connection between two points. Additionally, there is a margin around each polyline that triggers the tolltip before the pointer even touches the polyline (too improve touch action, I guess)
- A solution to the margin problem is to add positive and negative margins to each polyline point before comparing it to the pointer coordinates which improves the outcome but doesn't solve the main problem.
Sidenote:
- All routes are drawn into a single canvas
Long story short, I need external help to accomplish the goal. Maybe some of you have an idea or can provide a solution. Any input is appreciated.
** UPDATE: **
A working but pretty inefficient solution is as follows
Approach:
Calculate the shortest distance from the pointer to all routes in viewport. If distance from the pointer to a route is under a certain threshold, add them to the array of route labels that should be displayed.
Steps:
1.) bind a blank tooltip to the a feature group containing all routes
2.) bind mousemove event to the feature group with the follwing function
var routesFeatureGroup = L.featureGroup(routesGroup)
.bindTooltip('', {sticky: true})
.on('mousemove', function(e){
var routeLabels = [e.layer.options.label]; // add triggering route's label by default
var mouseCoordAbs = el.$map.project(e.latlng);
$.each(vars.objectsInViewport.routes, function(i, v){
if (e.layer.options.id != el.$routes[i].options.id && el.$routes[i]._pxBounds.contains(e.layerPoint)){
var nearestLatlngOnPolyline = getNearestPolylinePoint(e.latlng, el.$routes[i]);
var polyPointCoordAbs = el.$map.project(nearestLatlngOnPolyline);
var distToMouseX = polyPointCoordAbs.x - mouseCoordAbs.x;
var distToMouseY = polyPointCoordAbs.y - mouseCoordAbs.y;
var distToMouse = Math.sqrt(distToMouseX*distToMouseX + distToMouseY*distToMouseY);
if (distToMouse < 15) {
routeLabels.push(el.$routes[i].options.label);
}
}
})
var routesFeatureGroup.setTooltipContent(routeLabels.join('<br>'));
})
Explanation:
I already gather all objects (routes and markers) in the current viewport for another part of the app. All routes currently visible are stored in vars.objectsInViewport.routes (respectively their ids), so I dont have to go through all routes. The layer that triggered the mousemove event is added by default. I then check for each of the routes currently visible if:
- their id is different to the layer that trigger the mousemove event (as this label is added by default)
- if their bounds (in cartesian coordinates: "_pxBounds") contain the cartesian layerPoint of the mousemove event (for a rough approch to exclude routes that don't intersect)
If these conditions are met for a route, calculate the closest latlng point from the pointer to the route. I do this with a custom function, which is a bit to long to post it in this context. (I will if someone asks for it)
The mouse position and the latlng point on the polyline / route are then converted to absolute coordinates using the map-project method
http://leafletjs.com/reference.html#map-project
At last, the distance between these to points is calculated using pythagoras. It is pixel based, so that the zoom level isn't a factor. If the distance is below a certain threshold (15px) they are close enough to the pointer to be considered as being hovered (with the default margins around a polyline), so the label of the route is added to the label array.
Finally the tooltip for the feature group is filled with all labels.
Results are pretty promising even though the operation is pretty expensive. I added a timeout of 50ms to reduce the function call a bit:
var tooltipTimeout;
var routesFeatureGroup = L.featureGroup(routesGroup)
.bindTooltip('', {sticky: true})
.on('mousemove', function(e){
clearTimeout(tooltipTimeout);
tooltipTimeout = setTimeout(function(){
// collect labels
// ...
},50);
.on('mouseout', function(){
clearTimeout(tooltipTimeout);
})
I can give you an idea of how to do this, but I am not 100% sure that it will do the job. There is a plugin for Leaflet (Mapbox) that can tell you if a point is within a Polygon and it returns all the Polygons that contain that point.
If this plugin doesn't work for polylines you can create a polygon from a polyline by just going back from the last point to the first and closing the line (I am not sure if this suits you solution). For example if you have a polyline of connected points of [0, 1, 2, .... n-1, n] you then go back with connecting [n with n-1, n-1 with n-2, ... 1 with 0]. This way you will have the same shape of the polyline but it will be a polygon. This isn't the most optimized solution, it is a quick fix that uses a known and available plugin.
Once you get all the tooltips, you can open all of them at once for each polygon/polyline. Or maybe open some helper tooltip where the user can select which one he wants to open.
I hope this helps! If you figure out a better solution (or find a plugin that does the job) please post it here.

Leaflet - Fitbounds and keep center

I'm using Leaflet with Mapbox and I'd like to set the view of the map so :
all markers are visible
the center is set to a specific point
It's easy to do each points separately with setView and fitbounds but I don't know how to have both at the same time since setView changes the bounds and fitBounds changes the center. A solution could be to define a center and a zoom but how can I know which zoom will allow all my markers to be visible ?
EDIT
I implemented the solution suggested by IvanSanchez and it works as expected:
let ne=leafletBounds.getNorthEast();
let sw=leafletBounds.getSouthWest();
let neSymetric=[ne.lat + (center.lat - ne.lat)*2, ne.lng + (center.lng - ne.lng)*2];
let swSymetric=[sw.lat +(center.lat - sw.lat)*2, sw.lng + (center.lng - sw.lng)*2];
leafletBounds.extend(L.latLngBounds(swSymetric, neSymetric));
Get your bounds, and create a second L.Bounds instance by applying point symmetry along the centerpoint you want. Create a new L.Bounds containing the original bounds and the symmetric bounds. Run fitBounds() with that.
I found another solution to this. You can simply call map.panTo([lat, lng]) after you've adjusted your map with fitBound(). I am using VueJs and calling this in the mounted() lifecycle hook.
I am fitting bounds so you can see a user's location and also a geographic feature far away, but then I use panTo so the user's real location is at the center of the map after fitBounds. It seems to work seamlessly so far.