Cannot get features from building source layer in Mapbox GL - javascript

What I am trying to achieve here is to paint the building when someone searches an address. This can be achieved with map on click event. But it is not workable with geocoder result event. To get the features from building layer I have to pass {x, y} point to the layer which can be achieved with click event. But when I am using geocoder "result" event, it is giving {latitude, longitude} coordinates not {x, y} point. I also tried to convert these coordinates with map.project() but not correctly point. Is there workaround to achieve this? Checkout my code:
const bounds = [
[-97.846976993, 30.167105159], // Southwest coordinates
[-97.751211018, 30.242129961], // Northeast coordinates
];
const map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/smallcrowd/cl07a4926001b15pnu5we767g",
center: [-79.4512, 43.6568],
zoom: 13,
// maxBounds: bounds,
});
// Add the control to the map.
const geocoder = new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
mapboxgl: mapboxgl,
});
map.on("load", function () {
var layers = map.getStyle().layers;
var labelLayerId;
for (var i = 0; i < layers.length; i++) {
if (layers[i].type === "symbol" && layers[i].layout["text-field"]) {
labelLayerId = layers[i].id;
break;
}
}
map.addLayer(
{
id: "3d-buildings",
source: "composite",
"source-layer": "building",
type: "fill",
minzoom: 10,
paint: {
"fill-color": "#aaa",
},
},
labelLayerId
);
map.addSource("currentBuildings", {
type: "geojson",
data: {
type: "FeatureCollection",
features: [],
},
});
map.addLayer(
{
id: "highlight",
source: "currentBuildings",
type: "fill",
minzoom: 15,
paint: {
"fill-color": "#f00",
},
},
labelLayerId
);
// Working perfectly on click, it is painting the address but I do not want the address to be clicked rather it should be painted on searched.
map.on("click", "3d-buildings", (e) => {
map.getSource("currentBuildings").setData({
type: "FeatureCollection",
features: e.features,
});
});
//not working because the 3d-building layer wants input as x,y point which I tried to convert result's coordinates into point but map.project is giving wrong points as compared to mouse clicked points
geocoder.on("result", (e) => {
var coordinates = e.result.geometry.coordinates;
const point = map.project(coordinates);
const selectedFeatures = map.queryRenderedFeatures(point, {
layers: ["3d-buildings"],
});
console.log(point);
map.getSource("currentBuildings").setData({
type: "FeatureCollection",
features: selectedFeatures.features,
});
});
});
Any help will be appreciated !

So if I understand correctly:
User searches for an address
Map zooms to center around the chosen address
Now you want to know what is the screen X/Y coordinate of the chosen address
It's easy: it's exactly in the center of the viewport. So you can do just something like:
const x = map.getContainer().getClientRects()[0].width / 2;
const y = map.getContainer().getClientRects()[0].height / 2;
You will likely have to wait until the map actually finishes moving and the source features have loaded, after step 1. I would use map.once('idle', ...)

Related

Mapbox problem with creating PopUp for each cluster/marker with dynamic data

I have a problem where I am fetching my data from my API using WordPress. I have multiple clusters/markers on my map. But I am not able to create for each location a PopUp marker with the data coming from the API. I am facing some scoping issue where I want to have one popup dynamically show the data based ont he clicked marker if that makes sense.
Is there a trick on how to solve this?
import mapboxgl from 'mapbox-gl';
import MapboxLanguage from '#mapbox/mapbox-gl-language';
import apiFetch from '#wordpress/api-fetch';
(() => {
const mapContainer = document.querySelector('[data-gewoon-wonen]');
if (!mapContainer) {
return;
}
mapboxgl.accessToken = process.env.MAP_TOKEN_KEY;
const center = [4.387733, 51.862419];
const locations = {
type: 'FeatureCollection',
features: []
};
apiFetch({ path: '/wp-json/wp/v2/map?_embed' }).then((maps) => {
maps.forEach((item) => {
const {
id,
title: { rendered: title },
_embedded,
acf
} = item;
const image =
_embedded && _embedded['wp:featuredmedia'][0]?.source_url;
const {
map_location_subtitle: subtitle,
map_location_delivery: delivery,
map_location_project: project,
map_location_content: description,
map_location_coordinates_lat: lat,
map_location_coordinates_lng: lng,
map_location_status: status,
map_location_website: website
} = acf;
const getStatus = (currentStatus) => {
let statusObj = {
bouwfase: 'marker-gray',
planfase: 'marker-bright-pink',
opgeleverd: 'marker-bright-blue',
default: ''
};
let icon = statusObj[currentStatus] || statusObj['default'];
return icon;
};
const object = {
type: 'Feature',
properties: {
id,
status,
image,
icon: getStatus(status),
title,
subtitle,
project,
website,
delivery,
description
},
geometry: {
type: 'Point',
coordinates: [lng, lat]
}
};
locations.features.push(object);
});
});
const map = new mapboxgl.Map({
container: mapContainer,
style: 'mapbox://styles/theme/clcz9eocm000p14o3vh42tqfj',
center,
zoom: 10,
minZoom: 10,
maxZoom: 18,
attributionControl: false,
cooperativeGestures: true
});
map.addControl(
new MapboxLanguage({
defaultLanguage: 'mul'
})
);
map.on('load', () => {
// Add a new source from our GeoJSON data and
// set the 'cluster' option to true. GL-JS will
// add the point_count property to your source data.
map.addSource('locations', {
type: 'geojson',
// Point to GeoJSON data. This example visualizes all M1.0+ locations
// from 12/22/15 to 1/21/16 as logged by USGS' Earthquake hazards program.
data: locations,
cluster: true,
clusterMaxZoom: 14, // Max zoom to cluster points on
clusterRadius: 50 // Radius of each cluster when clustering points (defaults to 50)
});
map.addLayer({
id: 'clusters',
type: 'circle',
source: 'locations',
filter: ['has', 'point_count'],
paint: {
// Use step expressions (https://docs.mapbox.com/mapbox-gl-js/style-spec/#expressions-step)
// with three steps to implement three types of circles:
// * Blue, 20px circles when point count is less than 100
// * Yellow, 30px circles when point count is between 100 and 750
// * Pink, 40px circles when point count is greater than or equal to 750
'circle-color': [
'step',
['get', 'point_count'],
'#51bbd6',
100,
'#f1f075',
750,
'#f28cb1'
],
'circle-radius': [
'step',
['get', 'point_count'],
20,
100,
30,
750,
40
]
}
});
map.addLayer({
id: 'cluster-count',
type: 'symbol',
source: 'locations',
filter: ['has', 'point_count'],
layout: {
'text-field': ['get', 'point_count_abbreviated'],
'text-font': ['DIN Offc Pro Medium', 'Arial Unicode MS Bold'],
'text-size': 12
}
});
map.addLayer({
id: 'unclustered-point',
type: 'circle',
source: 'locations',
filter: ['!', ['has', 'point_count']],
paint: {
'circle-color': '#11b4da',
'circle-radius': 4,
'circle-stroke-width': 1,
'circle-stroke-color': '#fff'
}
});
// inspect a cluster on click
map.on('click', 'clusters', (e) => {
const features = map.queryRenderedFeatures(e.point, {
layers: ['clusters']
});
const clusterId = features[0].properties.cluster_id;
map.getSource('locations').getClusterExpansionZoom(
clusterId,
(err, zoom) => {
if (err) return;
map.easeTo({
center: features[0].geometry.coordinates,
zoom: zoom
});
}
);
});
// When a click event occurs on a feature in
// the unclustered-point layer, open a popup at
// the location of the feature, with
// description HTML from its properties.
map.on('click', 'unclustered-point', (e) => {
const coordinates = e.features[0].geometry.coordinates.slice();
const mag = e.features[0].properties.mag;
const tsunami =
e.features[0].properties.tsunami === 1 ? 'yes' : 'no';
// Ensure that if the map is zoomed out such that
// multiple copies of the feature are visible, the
// popup appears over the copy being pointed to.
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML(
`magnitude: ${mag}<br>Was there a tsunami?: ${tsunami}`
)
.addTo(map);
});
map.on('mouseenter', 'clusters', () => {
map.getCanvas().style.cursor = 'pointer';
});
map.on('mouseleave', 'clusters', () => {
map.getCanvas().style.cursor = '';
});
});
})();

Mapbox only visualize clusters in sight

I have this mapbox question which i haven't been able to solve.
I'm currently working on a little project where im using mapbox with clusters the code i have is from here: https://docs.mapbox.com/mapbox-gl-js/example/cluster/ it works fine but I thought is there a way to only load/visualize the clusters that are in my "view" ?
Example. I'm zoomed in on San francisco so it should only load/show clusters & points from there and not load them in New York too in order to make map faster.
mapboxgl.accessToken = 'token-goes-here';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/dark-v10',
center: [-103.5917, 40.6699],
zoom: 3
});
map.on('load', () => {
// Add a new source from our GeoJSON data and
// set the 'cluster' option to true. GL-JS will
// add the point_count property to your source data.
map.addSource('earthquakes', {
type: 'geojson',
// Point to GeoJSON data. This example visualizes all M1.0+ earthquakes
// from 12/22/15 to 1/21/16 as logged by USGS' Earthquake hazards program.
data: 'https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson',
cluster: true,
clusterMaxZoom: 14, // Max zoom to cluster points on
clusterRadius: 50 // Radius of each cluster when clustering points (defaults to 50)
});
map.addLayer({
id: 'clusters',
type: 'circle',
source: 'earthquakes',
filter: ['has', 'point_count'],
paint: {
// Use step expressions (https://docs.mapbox.com/mapbox-gl-js/style-spec/#expressions-step)
// with three steps to implement three types of circles:
// * Blue, 20px circles when point count is less than 100
// * Yellow, 30px circles when point count is between 100 and 750
// * Pink, 40px circles when point count is greater than or equal to 750
'circle-color': [
'step',
['get', 'point_count'],
'#51bbd6',
100,
'#f1f075',
750,
'#f28cb1'
],
'circle-radius': [
'step',
['get', 'point_count'],
20,
100,
30,
750,
40
]
}
});
map.addLayer({
id: 'cluster-count',
type: 'symbol',
source: 'earthquakes',
filter: ['has', 'point_count'],
layout: {
'text-field': '{point_count_abbreviated}',
'text-font': ['DIN Offc Pro Medium', 'Arial Unicode MS Bold'],
'text-size': 12
}
});
map.addLayer({
id: 'unclustered-point',
type: 'circle',
source: 'earthquakes',
filter: ['!', ['has', 'point_count']],
paint: {
'circle-color': '#11b4da',
'circle-radius': 4,
'circle-stroke-width': 1,
'circle-stroke-color': '#fff'
}
});
// inspect a cluster on click
map.on('click', 'clusters', (e) => {
const features = map.queryRenderedFeatures(e.point, {
layers: ['clusters']
});
const clusterId = features[0].properties.cluster_id;
map.getSource('earthquakes').getClusterExpansionZoom(
clusterId,
(err, zoom) => {
if (err) return;
map.easeTo({
center: features[0].geometry.coordinates,
zoom: zoom
});
}
);
});
// When a click event occurs on a feature in
// the unclustered-point layer, open a popup at
// the location of the feature, with
// description HTML from its properties.
map.on('click', 'unclustered-point', (e) => {
const coordinates = e.features[0].geometry.coordinates.slice();
const mag = e.features[0].properties.mag;
const tsunami =
e.features[0].properties.tsunami === 1 ? 'yes' : 'no';
// Ensure that if the map is zoomed out such that
// multiple copies of the feature are visible, the
// popup appears over the copy being pointed to.
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML(
`magnitude: ${mag}<br>Was there a tsunami?: ${tsunami}`
)
.addTo(map);
});
map.on('mouseenter', 'clusters', () => {
map.getCanvas().style.cursor = 'pointer';
});
map.on('mouseleave', 'clusters', () => {
map.getCanvas().style.cursor = '';
});
});
Here's your problem:
data: 'https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson',
So you're loading the whole GeoJSON at once. If you wanted to only load data for the current area you'd have to use vector tiles.
I'm zoomed in on San francisco so it should only load/show clusters & points from there and not load them in New York too in order to make map faster.
Mapbox GL JS won't waste effort trying to show things that are outside the current viewport. You don't need to worry about that.

mapbox geojson description for popup showing 'undefined'

I have the following code but when I click on a point to open a popup it returns 'undefined' and I cannot seem to work out why.
I'm pulling the description field from the geoJSON external source which I have control over but for some reason it just does not want to populate the description HTML in my array. I took the example for the popup from the mapbox website so I know it works there. I have checked, rechecked and triple checked but I think I cannot see the tree for the forest lol.
Could someone maybe help me please? thanks.
<script>
// ajax loading gif
$(document).ready(function () {
setTimeout(function () {
$("#ajax-loader").removeClass("is-active");
}, 6000);
});
// vars
var initialOpacity = 0.2;
var opacity = initialOpacity;
// mapbox api
mapboxgl.accessToken = "hidden_api_key";
var map = new mapboxgl.Map({
container: "map", // container ID
style: "mapbox://styles/mapbox/dark-v10",
center: [-2.582861, 53.5154517],
zoom: 5,
maxZoom: 16,
minZoom: 0,
});
map.on("load", function () {
// get hotspot locations
map.addSource("hotspot_locations", {
type: "geojson",
data: "https://netmaker.io/dashboard/public_actions.php?a=ajax_helium_miners_location",
cluster: false,
clusterMaxZoom: 10, // max zoom to cluster points on
clusterRadius: 50, // radius of each cluster when clustering points (defaults to 50)
});
// add 300m circle around each hotspot
map.addLayer({
id: "circle500",
type: "circle",
source: "hotspot_locations",
paint: {
"circle-radius": {
stops: [
[0, 1],
[16, 600],
],
base: 2,
},
"circle-color": "green",
"circle-opacity": 0.1,
"circle-stroke-width": 0,
"circle-stroke-color": "white",
},
});
// add hotspot location
map.addLayer({
id: "hotspots-layer",
type: "circle",
source: "hotspot_locations",
paint: {
"circle-radius": 2,
"circle-stroke-width": 2,
// "circle-color": "#36d293",
"circle-color": "white",
"circle-stroke-color": [
"match",
["get", "status"],
"online",
"#36d293",
"offline",
"#d23636",
"orange", // other
],
// "circle-stroke-color": '#36d293',
},
});
});
// ajax call hotspots location by name
var customData;
$.ajax({
async: false,
type: "GET",
global: false,
dataType: "json",
url: "https://netmaker.io/dashboard/public_actions.php?a=ajax_helium_miners_location_customdata",
success: function (data) {
customData = data;
},
});
// custom data using hotspot name
function forwardGeocoder(query) {
var matchingFeatures = [];
for (var i = 0; i < customData.features.length; i++) {
var feature = customData.features[i];
if (feature.properties.title.toLowerCase().search(query.toLowerCase()) !== -1) {
// feature["place_name"] = '<img src="https://netmaker.io/dashboard/images/helium_logo.svg" alt="" width="15px"> ' + feature.properties.title;
feature["place_name"] = feature.properties.title;
feature["center"] = feature.geometry.coordinates;
feature["place_type"] = ["hotspot"];
matchingFeatures.push(feature);
}
}
return matchingFeatures;
}
// add the control to the map.
map.addControl(
new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
localGeocoder: forwardGeocoder,
zoom: 14,
placeholder: "Search: address or hotspot name",
mapboxgl: mapboxgl,
})
);
map.on("click", "hotspots-layer", function (e) {
var coordinates = e.features[0].geometry.coordinates.slice();
var description = e.features[0].properties.description;
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
new mapboxgl.Popup().setLngLat(coordinates).setHTML(description).addTo(map);
});
map.on("mouseenter", "hotspots-layer", function () {
map.getCanvas().style.cursor = "pointer";
});
map.on("mouseleave", "hotspots-layer", function () {
map.getCanvas().style.cursor = "";
});
</script>
You're recieving an undefined because e.features[0].properties.description doesn't exist in the "hotspots-layer" data.
"features": [
{
"type": "Feature",
"properties": {
"status": "online"
},
"geometry": {
"type": "Point",
"coordinates": [
"119.73479929772",
"30.240836896893",
0
]
}
},
The only "description" in this case that you can return is the e.features[0].properties.status as seen here:
map.on("click", "hotspots-layer", function (e) {
var coordinates = e.features[0].geometry.coordinates.slice();
var description = e.features[0].properties.status;
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
console.log(description)
new mapboxgl.Popup().setLngLat(coordinates).setHTML(description).addTo(map);
});
This code snippet will allow the click event to show you the status when you interact with the hotspot location.

Given the following Leaflet.Draw example on Plunker, how would I catch the rectangle created event and action on it?

Plunker Example:
Leaflet Draw plugin with OSM map
var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
osmAttrib = '© OpenStreetMap contributors',
osm = L.tileLayer(osmUrl, { maxZoom: 18, attribution: osmAttrib });
var map = new L.Map('leaflet', { layers: [osm], center: new L.LatLng(52.105289405897, 5.2629891004852425), zoom: 13 });
console.log('map ready');
var drawnItems = new L.FeatureGroup();
var coords = [new L.latLng(51.2, 4.5), new L.latLng(51.2, 4.6), new L.latLng(51.2, 4.9)];
var poly = new L.Polyline(coords, {
color: 'blue',
opacity: 1,
weight: 5
});
drawnItems.addLayer(poly);
map.addLayer(drawnItems);
var drawControl = new L.Control.Draw({
draw: {
position: 'right',
polygon: {
title: 'Polygon',
allowIntersection: false,
drawError: {
color: '#b00b00',
timeout: 1000
},
shapeOptions: {
color: '#bada55'
},
showArea: true
},
polyline: {
metric: false
},
circle: {
shapeOptions: {
color: '#662d91'
}
}
},
edit: {
featureGroup: drawnItems
}
});
map.addControl(drawControl);
map.on('draw:created', function (e) {
var type = e.layerType,
layer = e.layer;
if (type === 'marker') {
layer.bindPopup('A popup!');
}
drawnItems.addLayer(layer);
console.log('adding layer', layer, drawnItems);
});
I need to catch a created rectangle and ultimately make a file out of it's coordinates, but for now I'm trying to figure out how to catch the event and output the rectangles coordinates to the console.
Forgive me, still stepping into Javascript. Thanks
--Edit--
So I see how to log this event to console, but I don't clearly see how to access the lat/lng info from the event.
map.on('draw:rectangle-created', function (e) {
console.log(e.rectangle-created);
});
Just use the draw:created event and check if type is a rectangle:
map.on('draw:created', function (e) {
var type = e.layerType,
layer = e.layer;
if (type === 'rectangle') {
// It's a rectangle, do stuff
console.log(layer.getLatLngs());
}
drawnItems.addLayer(layer);
console.log('adding layer', layer, drawnItems);
});
You can access the rectangle's coordinates by calling the getLatLngs method. It returns an array of L.LatLng objects:
rectangle.getLatLngs().forEach(function (latlng) {
console.log(latlng.lat); //latitude
console.log(latlng.lng); //longitude
});
http://leafletjs.com/reference.html#latlng

What is the simplest way to initialize a map, add a marker and then clear the marker?

We have a page with a list of establishments. There is a button that is labeled, "map". When a user clicks on it, we have a Jquery Dialog window appearing and we have a Mapbox map appearing in that window with a single marker indicating the location of the establishment.
The issue is that the markers are not getting cleared out, so that by the third time a user clicks on the "map" button there are 3 markers on the map.
We are wondering
How to properly clear the map of all markers and
How to center the map on the marker
We are using the following:
Initializing map
var map = L.mapbox.map('map', 'our-map')
.setView([49.2500, -123.1000], 9);
When a user click's on a button, this adds the marker to the map:
jQuery('.map-button').click(function(){
//jQuery(this.addClass("active"));
var lat = jQuery(this).attr('data-lat');
var long = jQuery(this).attr('data-long');
var markerLayers = L.mapbox.markerLayer({
// this feature is in the GeoJSON format: see geojson.org
// for the full specification
type: 'Feature',
geometry: {
type: 'Point',
// coordinates here are in longitude, latitude order because
// x, y is the standard for GeoJSON and many formats
coordinates: [long, lat ]
},
properties: {
title: 'A Single Marker',
description: 'Just one of me',
// one can customize markers by adding simplestyle properties
// http://mapbox.com/developers/simplestyle/
'marker-size': 'large',
'marker-color': '#008000'
}
}).addTo(map);
UPDATED CODE
<script>
var markerLayer = L.mapbox.markerLayer({
type: 'FeatureCollection',
features: {
}
}).addTo(map);
jQuery('.map-button').click(function(){
//jQuery(this.addClass("active"));
var lat = jQuery(this).attr('data-lat');
var long = jQuery(this).attr('data-long');
var geojson = [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [long,lat]
},
"properties": {
"marker-color": "#008000",
"marker-size": "large",
}
}
];
markerLayer.setGeoJSON(geojson);
map.setView([long, lat ], 9);
//map.setView([long, lat ], 9);
//alert(jQuery(this).attr('data-lat'));
})
jQuery('#dialog-modal').live("dialogclose", function(){
//jQuery('.leaflet-marker-icon').hide();
markerLayer.clearLayers();
});
To set the center of the map:
map.setView([long, lat ], 9);
And to clear the markers in a layer:
markerLayers.clearLayers();

Categories

Resources