Mapbox GL JS: zoom to filtered polygon? - mapbox

I am using Mapbox GL JS to display a polygon layer. I would to allow the user to choose a name from a dropdown, and then highlight and zoom to the matching polygon.
I already know how to highlight the matching polygon using map.setFilter, but I don't know how to zoom to the bounds of the matching polygon. This is my current code:
map.addLayer({
'id': 'polygon_hover',
'source': 'mysource',
'source-layer': 'mylayer',
'type': 'fill',
'paint': {
'fill-color': 'red',
"fill-opacity": 0.6
},
"filter": ["==", 'CUSTNAME', ""]
});
// Get details from dropdown
custname.on("change", function(e) {
// get details of name from select event
map.setFilter('polygon_hover', ["==", 'CUSTNAME', name]);
// Get bounds of filtered polygon somehow?
// var bounds = ??;
// map.fitBounds(bounds);
});
I have examined the Mapbox example of zooming to bounds, but it assumes that you already know what the bounds are.
Is there any way it's possible to get the bounds of the polygon matching a map filter in Mapbox?

I've the following code to fitBounds to Polygon center coords:
var coordinates = f.geometry.coordinates[0];
var bounds = coordinates.reduce(function (bounds, coord) {
return bounds.extend(coord);
}, new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]));
map.fitBounds(bounds, {
padding: 20
});
Where f is one Feature.

I found a solution to your problem. Leaflet has a polygon Class which takes an Array of polygon coordinates and has a function called getBounds() that returns south west and north east bounds. However, Leaflet doesn't follow the convention of LngLat, its format is LatLng. Therefore, you have to switch it. I took an example out from Mapbox Show drawn polygon area, and added exactly what you're looking for.
var polygon = data.features[0].geometry.coordinates;
var fit = new L.Polygon(polygon).getBounds();
var southWest = new mapboxgl.LngLat(fit['_southWest']['lat'], fit['_southWest']['lng']);
var northEast = new mapboxgl.LngLat(fit['_northEast']['lat'], fit['_northEast']['lng']);
var center = new mapboxgl.LngLatBounds(southWest, northEast).getCenter();
// map.flyTo({center: center, zoom: 10});
map.fitBounds(new mapboxgl.LngLatBounds(southWest, northEast));

I see that the question is still relevant - I solved it making a separate request to the database containing all points of a given polygon and building bounds [[minLng, minLat], [maxLng, maxLat]].
All attempts to address geometry of already rendered or source features didn't work for me - most probably because Mapbox doesn't keep initial geoJSON in the tiles.

Related

How I can I get geojson boundary array from existing layer using mapbox gl?

I am using one of the custom tileset of tilling service in mapbox. I loaded that custom tile layer in map using below code.
map.addSource('california', {
type: 'vector',
url: 'mapbox://xyz.california'
});
map.addLayer({
'id': 'terrain-data',
'type': 'fill',
'source': 'california',
'source-layer': 'california',
'layout': {},
'paint': {
'fill-color': 'black',
'fill-opacity': 0.5
}
});
Above code is filling out the inner area with black color. But I want to fill out the outer area of that polygon. Only one way I know to do that is getting difference of whole map with that polygon by using turf.js. After that I will be able to fill the outside area.
Now the question is how can I get the geojson ploygon array of above added layer? So I can calculate the difference.
You can't easily get the complete geometry of a polygon from a vector tile set, because it has already been cut up into tiles. You would have to either find a way to merge them together, or get your geometry into the front end as a complete geojson first.

Mapbox-gl fill layer distorts rendering on higher zoom

I'm using mapbox-gl version 0.46.0-beta.1 (With ReactJS).
I've drawn simple fill layers using GeoJSON source.
The coordinates used to draw the fill are
Coordinates Data:
At a specific zoom level, the polygon renders as expected.
Expected Layer:
But on zooming in, the polygon distorts.
Distorted Fill Layer:
The code I'm using is:
`let paint = {
'fill-color': 'Some Color',
'fill-opacity': 0.4,
'fill-outline-color': 'Some Color'
}
let uniqueID = 'someuniqueID';
map.addLayer({
'id': uniqueID,
'type': 'fill',
'source': {
'type': 'geojson',
'data': {
'type': 'Feature',
'geometry': {
'type': 'Polygon',
'coordinates': [polyCoords]
}
}
},
'paint': paint
})`
We were able to solve the same problem by making sure the first point in the polygon is also the last. For this polygon, you should add the point:
[28.6045067810482..., 77.3860210554725...]
I also had this issue. For a bounding box of coordinates for mapbox, having just the 4 coordinate pairs to create the polygon does create rendering artifacts, directly like above. When making your coordinate bounding box as a polygon, be sure to enter a 5th record, which would be the same as your coordinate at coor[0], where coor is your array of coordinate pairs. You will only notice the weird rendering and re-drawing when zooming, this in fact made it go away for me.
For example:
var coors = [[+sw_lng, +sw_lat], [+sw_lng, +ne_lat], [+ne_lng, +ne_lat], [+ne_lng, +sw_lat]]; //makes a 4 pointed polygon
coors.push(coors[0]); //then continue

How to draw a path between two nodes using Leaflet

I have a set of lat and long points which form a route from source to destination. I have used polyline method of Leaflet to draw the path between the source to destination, but it gives a scrambled path.
var firstpolyline = new L.polyline(latlong, {
color: 'red',
weight: 3,
opacity: 0.5,
smoothFactor: 1
});
firstpolyline.addTo(mym[![enter image description here][1]][1]ap);
The latlong in the above code is an array of latitude and longitude points. But it gives a scrambled output like this:
imgur.com/aZrGa.jpg
But the latlong points form a single correct path from source to destination. I have been using polyLine. What mistake am I doing? Should I use some other methods of Leaflet?
Edit after #ivansanchez comment
The latlong arrays are of type L.LatLng(x,y) where L is the Leaflet object. Here is a snippet:
1. var mymap = L.map('mapid').setView([17.387140, 78.491684], 13);
2. L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: "© <a href='http://osm.org/copyright'>OpenStreetMap</a> contributors"
}).addTo(mymap);
3. var latlngs = [
[15.89625,80.53544],
[15.89626,80.53542],
[15.89628,80.53536],
[15.89617,80.53539],
[15.89621,80.53547]
];
4. var path = L.polyline.antPath(latlngs,{"delay":400,"dashArray":[10,20],"weight":5,"color":"black","paused":true,"reverse":false}
).addTo(mymap);
5. mymap.addLayer(path);
mymap.fitBounds(path.getBounds());
EXPLANATION:
To set the map view on given latlongs([17.387140, 78.491684]), 13 means zoom.
Adding tiles on the maps.
Latlongs.
Drawing polylines ant paths by setting css.
Add the layer to the path.
It was my mistake, Polyline works properly. I had an array of latlng that were not in an order. Putting an ordered latlng points helped me plot the route correctly between source and destination.

style a geojson point like a POI with leaflet/mapbox

I am using mapbox.js to render a mapbox map. I am trying to load geojson from my server that contain either a country polygon or a city coordinates (lon,lat).
I have been able to style the country polygons but not the city points/markers.
I am not able to modify the geojson to use mapbox simplestyle
Here is the code executed when the page loads (I changed the mapbox map ID):
var southWest = L.latLng(-90, -360), northEast = L.latLng(90, 360);
var bounds = L.latLngBounds(southWest, northEast);
var map = L.mapbox.map('map', 'MapboxMapID', { zoomControl: false, infoControl: true, detectRetina: true, maxBounds: bounds, minZoom: 2, legendControl: {position: 'topright'}});
new L.Control.Zoom({ position: 'bottomright' }).addTo(map);
map.fitBounds(bounds);
var locationsGroup = L.featureGroup().addTo(map);
and then when the user selects a country or city with a selectbox:
$("#select2-search-up").on("change", function (e) {
if (e.added) {
var location = L.mapbox.featureLayer().loadURL('/citiesCountriesID/' + e.added.id).on('ready', function(featLayer) {
this.eachLayer(function(polygon) {
polygon.setStyle({
stroke:false, fillColor:'red', fillOpacity:0.2
});
});
});
locationsGroup.addLayer(location);
} else {
locationsGroup.eachLayer(function (layer) {
if (layer._geojson[0]._id == e.removed.id) {
locationsGroup.removeLayer(layer);
}
});
}
});
Ideally I would like to display a different icon that the standard marker, but I could do with a small red square
Thank you for your inputs
In this example I did some circle markers but I'm pretty sure you can do other basic svg shps or your own .png pretty easy. http://bl.ocks.org/mpmckenna8/db2eef40314fe24e9177
This example from Mapbox also shows how to use a icon from their icon Library which has a lot of choices also. https://www.mapbox.com/mapbox.js/example/v1.0.0/l-mapbox-marker/
It might also help to see some of your geojson structure to see why it can't use simplestyle
In my bl.ocks example I loaded each of the geojson datasets separately
var begin = L.geoJson(start,{
pointToLayer:function(feature, latlng){
return L.circleMarker(latlng,{
radius:9,
fillColor: "orange",
fillOpacity:.7
})
}
})
Is how I set up my circles and I set a different L.geoJson to the other data which I left as the default markers.

Start-Marker from geojson polyline

i have a map with some walking- and bike-routes and popups with a few details an a pic. Now i want to set a marker on the first vertex of a geojson polyline, but i cant find out how. Btw. i´m new to leaflet/mapbox, and i put my map togehter from code snippets.
Here is the map now:
This is how i create the polylines now. I call them via layercontrol.
var mtb = L.geoJson(radjs, {
filter: function (feature, layer) {
if (feature.properties) {
// If the property "underConstruction" exists and is true, return false (don't render features under construction)
return feature.properties.typ === 'mtb';
}
return true;
},
style: {
"color": '#6699cc',
dashArray: '',
"weight": 4,
"opacity": 0.6
}, onEachFeature: onEachFeature2}).addTo(rad);
Thank you for your help,
Marc
You could just add a Feature to your geojson with the latitude and longitude like the do it in the Leaflet GeoJSON Example.
Probably it will be more convenient to read the geometry.coordinates from geojson features and define a new marker.
Beside you have an error on line 569. You should change:
var map = L.mapbox.map('map','',{
to:
var map = L.mapbox.map('map',null,{
Create a simple marker object and add it to the map.
marker = L.marker([0, 0], {
icon: L.mapbox.marker.icon()
}).addTo(map)
Then set the latitude and longitude to the first coordinates of your geoJSON. Assuming your geoJSON is set to the var geojson, you can access the coordinates by indexing into the array.
marker.setLatLng(L.latLng(
geojson.coordinates[0][1],
geojson.coordinates[0][0]))