How to filter mapbox fetaure using radius and latlng - mapbox-gl-js

I have a layer on mapbox studio containing all the postal code plotted on the map and I am accessing it using access key and layer id ,
I want to filter out only the postal code (marker) inside a radius

Turf provides a pointsWithinPolygon() function, that helps you to find any points within the circle. Here is an example:
mapboxgl.accessToken = 'pk.eyJ1IjoicGFybmRlcHUiLCJhIjoiY2l6dXZ5OXVkMDByZDMycXI2NGgyOGdyNiJ9.jyTchGQ8N1gjPdra98qRYg';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v10',
center: [-46.6062, -23.5513],
zoom: 11
});
map.on('load', function () {
// List of your marker locations
var points = turf.points([
[-46.6318, -23.5523],
[-46.6246, -23.5325],
[-46.6062, -23.5513],
[-46.663, -23.554],
[-46.643, -23.557]
]);
// Create circle with radius
var center = [-46.6062, -23.5513];
var radius = 3;
var options = {steps: 10, units: 'kilometers', properties: {foo: 'bar'}};
var circle = turf.circle(center, radius, options);
// Find point within circle
var markerWithin = turf.pointsWithinPolygon(points, circle);
console.log("Found: " + markerWithin.features.length + " points");
// Draw circle polygon
map.addLayer({
'id': 'circle',
'type': 'fill',
'source': {
'type': 'geojson',
'data': circle
},
'layout': {},
'paint': {
'fill-color': '#525252',
'fill-opacity': 0.2
}
});
// Draw all points
map.addLayer({
'id': 'points',
'type': 'circle',
'source': {
'type': 'geojson',
'data': points
},
'layout': {},
'paint': {
'circle-radius': 5,
'circle-color': 'red',
'circle-opacity': 1
}
});
// Draw marker with in circle
markerWithin.features.forEach(function(marker) {
// Create marker
new mapboxgl.Marker()
.setLngLat(marker.geometry.coordinates)
.addTo(map);
});
});
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; };
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v1.5.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.5.0/mapbox-gl.css' rel='stylesheet' />
<script src='https://npmcdn.com/#turf/turf/turf.min.js'></script>
<div id='map'></div>

Related

Cluster creation in openlayer 6.4.3 - Uncaught TypeError: this.source.loadFeatures is not a function

I am trying to create cluster using ol 6.4.3. My script is
var cluster_data = {
"type": "Feature",
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [686213.47091037, 1093486.3776117],
},
},
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [687067.04391223, 1094462.7275206],
},
},
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [687214.60645801, 1094362.868384],
},
}
],
};
var features = new Array(3);
var source = new ol.layer.Vector({
features: new ol.format.GeoJSON().readFeatures(cluster_data),
});
var clusterSource = new ol.source.Cluster({
distance: 40,
source: source,
});
var styleCache = {};
var clusters = new ol.layer.Vector({
source: clusterSource,
style: function (feature) {
var size = feature.get('features').length;
var style = styleCache[size];
if (!style) {
style = new Style({
image: new CircleStyle({
radius: 10,
stroke: new Stroke({
color: '#fff',
}),
fill: new Fill({
color: '#3399CC',
}),
}),
text: new Text({
text: size.toString(),
fill: new Fill({
color: '#fff',
}),
}),
});
styleCache[size] = style;
}
return style;
},
});
map.addLayer(clusters);
I have added other 3 Tile layers map.getLayers().extend([bm,road,landmark]); and trying to add cluster over this. But getting error Uncaught TypeError: this.source.loadFeatures is not a function while adding cluster.
The map I got after adding my layer is
The error is because
var source = new ol.layer.Vector({
should be
var source = new ol.source.Vector({
Also the first type in the data before the features should be
"type": "FeatureCollection",
And if you are using the OpenLayers full build
new Style new CircleStyle new Stroke new Fill and new Text
should be
new ol.style.Style new ol.style.Circle new ol.style.Stroke new ol.style.Fill and new ol.style.Text
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://openlayers.org/en/v6.4.3/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v6.4.3/build/ol.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.6.1/proj4.js"></script>
<style>
html, body, .map {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script>
proj4.defs("EPSG:32643","+proj=utm +zone=43 +datum=WGS84 +units=m +no_defs");
ol.proj.proj4.register(proj4);
var cluster_data = {
"type": "FeatureCollection",
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [686213.47091037, 1093486.3776117],
},
},
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [687067.04391223, 1094462.7275206],
},
},
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [687214.60645801, 1094362.868384],
},
}
],
};
var source = new ol.source.Vector({
features: new ol.format.GeoJSON().readFeatures(cluster_data),
});
var clusterSource = new ol.source.Cluster({
distance: 40,
source: source,
});
var styleCache = {};
var clusters = new ol.layer.Vector({
source: clusterSource,
style: function (feature) {
var size = feature.get('features').length;
var style = styleCache[size];
if (!style) {
style = new ol.style.Style({
image: new ol.style.Circle({
radius: 10,
stroke: new ol.style.Stroke({
color: '#fff',
}),
fill: new ol.style.Fill({
color: '#3399CC',
}),
}),
text: new ol.style.Text({
text: size.toString(),
fill: new ol.style.Fill({
color: '#fff',
}),
}),
});
styleCache[size] = style;
}
return style;
},
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
projection: "EPSG:32643"
})
});
map.addLayer(clusters);
map.getView().fit(source.getExtent());
map.getView().setZoom(map.getView().getZoom() - 6);
</script>
</body>
</html>

Can't get properties from external geojson to mapbox

I have replicate and adjust this example from mapbox:
https://docs.mapbox.com/mapbox-gl-js/example/filter-markers/
Everything is working fine but I want to have the geojson as an external file.
So I change this code:
var places = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'properties': {
'icon': 'theatre'
},
'geometry': {
'type': 'Point',
'coordinates': [-77.038659, 38.931567]
}
},
]
};
with this:
var places = '../images/destinations.geojson';
and I get this error in DevTools: Uncaught TypeError: Cannot read property 'forEach' of undefined.
The rest of the code (that I get the error) is this:
map.on('load', function() {
// Add a GeoJSON source containing place coordinates and information.
map.addSource('places', {
'type': 'geojson',
'data': places
});
places.features.forEach(function(feature) {
var symbol = feature.properties['icon'];
var layerID = 'poi-' + symbol;
// Add a layer for this symbol type if it hasn't been added already.
if (!map.getLayer(layerID)) {
map.addLayer({
'id': layerID,
'type': 'symbol',
'source': 'places',
'layout': {
'icon-image': symbol + '-15',
'icon-allow-overlap': true
},
'filter': ['==', 'icon', symbol]
});
One way to load an external geoJSON file would be to use d3js. See the example below, which is taken from this mapbox example. This example will draw a line for the coordinates given in the geoJSON file.
You should be able to iterate over data.features with your forEach loop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Load from an external geoJSON</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://api.mapbox.com/mapbox-gl-js/v1.8.0/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v1.8.0/mapbox-gl.css" rel="stylesheet" />
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
mapboxgl.accessToken = '<access_token>';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/satellite-v9',
zoom: 0
});
map.on('load', function() {
// We use D3 to fetch the JSON here so that we can parse and use it separately
// from GL JS's use in the added source. You can use any request method (library
// or otherwise) that you want.
d3.json(
'https://docs.mapbox.com/mapbox-gl-js/assets/hike.geojson', //the geoJSON data file
function(err, data) {
if (err) throw err;
// save full coordinate list for later
var coordinates = data.features[0].geometry.coordinates;
// start by showing just the first coordinate
data.features[0].geometry.coordinates = [coordinates[0]];
// add it to the map
map.addSource('trace', { type: 'geojson', data: data });
map.addLayer({
'id': 'trace',
'type': 'line',
'source': 'trace',
'paint': {
'line-color': 'yellow',
'line-opacity': 0.75,
'line-width': 5
}
});
}
);
});
</script>
</body>
</html>

Adding multiple sources and layers with .each?

I try to simplify my codebase for an ongoing project. I render different lines from different sources. Adding the source and layer one by one works as expected. But if I put this in an object it won't work. I even have no errors in the console. Now I am stuck at the following code
var trip_entries = {
t2: {
trip_id: 'trip-entry-2',
trip_geojson: '[[-0.15591514, 51.51830379],[-0.07571203, 51.51424049],[-0.08533793, 51.50438536],[-0.085793, 51.5036],[-0.084793, 51.503336],[-0.089793, 51.505336]]'
},
t3: {
trip_id: 'trip-entry-3',
trip_geojson: '[[-0.15514, 51.518],[-0.075703, 51.515],[-0.085793, 51.50],[-0.0793, 51.506],[-0.08473, 51.50336],[-0.0893, 51.536]]'
},
};
// Set route
$.each(trip_entries,function(key,value){
// Add sources
map.addSource(value.trip_id,{
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'LineString',
'coordinates': value.trip_geojson
}
},
],
},
});
// Add layers
map.addLayer({
'id': value.trip_id,
'type': 'line',
'source': value.trip_id,
'layout': {
'line-join': 'round',
'line-cap': 'round'
},
'paint': {
'line-color': 'rgb(160,160,160)',
'line-width': 6,
}
});
});
You are passing the geoJSON as a string, rather than an array of coordinates. You should remove the ' ' on both of your geoJSONs to get the code to run. See below:
mapboxgl.accessToken =
"pk.eyJ1IjoicGxtYXBib3giLCJhIjoiY2s3MHkzZ3VnMDFlbDNmbzNiajN5dm9lOCJ9.nbbtDF54HIXo0mCiekVxng";
var map = new mapboxgl.Map({
container: "map", // container id
style: "mapbox://styles/mapbox/streets-v11", // stylesheet location
center: [-0.084793, 51.503336], // starting position [lng, lat]
zoom: 11 // starting zoom
});
var trip_entries = {
t2: {
trip_id: "trip-entry-2",
trip_geojson: [
[-0.15591514, 51.51830379],
[-0.07571203, 51.51424049],
[-0.08533793, 51.50438536],
[-0.085793, 51.5036],
[-0.084793, 51.503336],
[-0.089793, 51.505336]
]
},
t3: {
trip_id: "trip-entry-3",
trip_geojson: [
[-0.15514, 51.518],
[-0.075703, 51.515],
[-0.085793, 51.5],
[-0.0793, 51.506],
[-0.08473, 51.50336],
[-0.0893, 51.536]
]
}
};
map.on("load", function () {
// Set route
$.each(trip_entries, function (key, value) {
// Add sources
map.addSource(value.trip_id, {
type: "geojson",
data: {
type: "FeatureCollection",
features: [
{
type: "Feature",
geometry: {
type: "LineString",
coordinates: value.trip_geojson
}
}
]
}
});
// Add layers
map.addLayer({
id: value.trip_id,
type: "line",
source: value.trip_id,
layout: {
"line-join": "round",
"line-cap": "round"
},
paint: {
"line-color": "rgb(160,160,160)",
"line-width": 6
}
});
});
});
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://api.mapbox.com/mapbox-gl-js/v1.9.1/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v1.9.1/mapbox-gl.css" rel="stylesheet" />
<div id="map"></div>

How can I load Baidu basemap tiles with mapboxgl?

I want to load Baidu basemap tiles with mapboxgl, but due to the problem of the coordinate system, there is a serious offset of the tiles. what should I do?
let simple = {
'version': 8,
'sources': {
'source': {
'type': 'raster',
'tiles': ['http://online0.map.bdimg.com/tile/?qt=tile&x={x}&y={y}&z={z}&styles=sl&v=017&udt=20130712'],
}
},
'layers': [
{
'id': 'layer',
'type': 'raster',
'source': 'source',
'minzoom': 0,
'maxzoom': 18,
'interactive': true
}]
}
mapboxgl.accessToken = 'pk.eyJ1IjoiY2h5eXpsMDgwOSIsImEiOiJjanAxemEyYnQwMWZvM3Fudzh5c3ZvbHJqIn0.j2i8D_Gcam955rcEt2k_mA';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [-74.50, 40],
zoom: 9
});

Simply adding points tileset layer with Mapbox js

I need to simply add a tileset of points.
No idea why I'm not able to do this.
Here's the fiddle, below is the js code.
https://jsfiddle.net/qaehnvs9/3/
mapboxgl.accessToken = 'pk.eyJ1IjoibW9sbHltZXJwIiwiYSI6ImNpazdqbGtiZTAxbGNocm0ybXJ3MnNzOHAifQ.5_kJrEENbBWtqTZEv7g1-w'
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v9',
hash: true,
center: [0,0],
zoom: 1,
pitchWithRotate: false,
})
/////////////////////////////////////////////////////////////
//Global Settlements
/////////////////////////////////////////////////////////////
map.on('load', function () {
map.addLayer({
'id': 'global_settlements_id',
'source': {
'type': 'vector',
'url': 'mapbox://nittyjee.c9okffto'
},
//'source-layer': 'shapefile_export-4f28wr',
'source-layer': 'shp-2lsmbo',
'type': 'symbol',
'maxzoom': 6,
'layout': {
'symbol-placement': 'point',
}
});
});
For dots/points, I needed to add it as a circle type.
Updated fiddle: https://jsfiddle.net/qaehnvs9/4/
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v9',
hash: true,
center: [0,0],
zoom: 1,
pitchWithRotate: false,
})
/////////////////////////////////////////////////////////////
//Global Settlements
/////////////////////////////////////////////////////////////
map.on('load', function () {
map.addLayer({
'id': 'global_settlements_id',
'type': 'circle',
'source': {
type: 'vector',
url: 'mapbox://nittyjee.c9okffto'
},
'source-layer': 'shp-2lsmbo',
'paint': {
'circle-radius': 4,
'circle-color': '#e55e5e'
}
});
});