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.
Related
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 = '';
});
});
})();
I try to import styling with the stylingfunction from ol-mapbox-style. But it doesn't work.
- Without the stylesection the map renders perfectly fine as just the vector lines
- With the stylesection included the browser doesn't show the map
Please see the code below:
var stylefunction = olms.stylefunction;
var {applyStyle} = olms;
var {apply} = olms;
var key = 'my-key';
const map = new Map({
target: 'map',
view: new View({
center: fromLonLat([5.058510183635008, 52.30659202560312]),
zoom: 14
})
});
const layer = new VectorTileLayer({
source: new VectorTileSource({
attributions: '',
format: new GeoJSON(),
maxZoom: 19,
url: 'https://tile.nextzen.org/tilezen/vector/v1/all/{z}/{x}/{y}.json?api_key=' + key,
tileLoadFunction: function(tile, url) {
tile.setLoader(function(extent, resolution, projection) {
fetch(url).then(function(response) {
response.text().then(function(data) {
const jsons = JSON.parse(data);
const format = tile.getFormat();
const layers = ['water', 'roads', 'buildings'];
const features = [];
layers.forEach(function(layer) {
const layerFeatures = format.readFeatures(jsons[layer], {
featureProjection: projection
});
layerFeatures.forEach(function(feature) {
feature.set('layer', layer);
features.push(feature);
});
});
tile.setFeatures(features);
});
});
});
}
})
});
map.addLayer(layer);
fetch('./static/bright.json')
.then(r => r.json())
.then((glStyle) => {
stylefunction(layer, glStyle, 'bright');
if (map.getLayers().getArray().indexOf(layer) === -1) {
map.addLayer(layer);
}
});
And see here below the first lines of bright.json which i'm trying to use as a testfile.
{
"glyphs": "https://maps.tilehosting.com/fonts/{fontstack}/{range}.pbf?key=",
"name": "bright",
"layers": [
{
"id": "background",
"paint": {
"background-color": "#f8f4f0"
},
"type": "background"
},
{
"filter": [
"==",
"subclass",
"glacier"
],
"id": "landcover-glacier",
"layout": {
"visibility": "visible"
},
"metadata": {
"mapbox:group": "1444849388993.3071"
},
"paint": {
"fill-color": "#fff",
"fill-opacity": {
"base": 1,
"stops": [
[
0,
0.9
],
[
10,
0.3
]
]
}
},
"source": "openmaptiles",
I am using Leaflet javascript library to show some earthquake information. You are able to see few red circles on map. When you click that red circle it will display few details in popup.
I want to show the popup when you click the link from outside of map. This (answer) is useful. But, I want to achieve it without ID? I mean if i have more than 30 markers on map and also I don't have any ID, just class names in my links. How do I trigger popup when I click a link from outside of map?
This (answer) is good. In this answer they mentioned marker 1, marker 2 and marker 3. But, In my case I don't know how many markers will show. Sometimes 5, 50, 100 or may be more than 150. Thats why I have asked this question.
<html>
<head>
<meta charset="utf-8" />
<title>Leaflet</title>
<link
rel="stylesheet"
href="https://unpkg.com/leaflet#1.5.1/dist/leaflet.css"
integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
crossorigin=""
/>
<script
src="https://unpkg.com/leaflet#1.5.1/dist/leaflet.js"
integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og=="
crossorigin=""
></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<div id="map" style="width: 400px; height: 400px;"></div>
<script>
var object = {
type: "FeatureCollection",
metadata: {
generated: 1564051101000,
url:
"https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2019-07-20&endtime=2019-07-21&minmagnitude=5",
title: "USGS Earthquakes",
status: 200,
api: "1.8.1",
count: 4
},
features: [
{
type: "Feature",
properties: {
mag: 5.2000000000000002,
place: "79km ENE of L'Esperance Rock, New Zealand",
time: 1563662132538,
updated: 1563663302040,
tz: -720,
url: "https://earthquake.usgs.gov/earthquakes/eventpage/us70004pu1",
detail: "https://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us70004pu1&format=geojson",
felt: null,
cdi: null,
mmi: null,
alert: null,
status: "reviewed",
tsunami: 0,
sig: 416,
net: "us",
code: "70004pu1",
ids: ",us70004pu1,",
sources: ",us,",
types: ",geoserve,origin,phase-data,",
nst: null,
dmin: 1.9299999999999999,
rms: 1.28,
gap: 70,
magType: "mww",
type: "earthquake",
title: "M 5.2 - 79km ENE of L'Esperance Rock, New Zealand"
},
geometry: { type: "Point", coordinates: [-178.1173, -31.174800000000001, 35] },
id: "us70004pu1"
},
{
type: "Feature",
properties: {
mag: 5.5999999999999996,
place: "23km NNW of Kandrian, Papua New Guinea",
time: 1563655424914,
updated: 1563741959328,
tz: 600,
url: "https://earthquake.usgs.gov/earthquakes/eventpage/us70004psn",
detail: "https://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us70004psn&format=geojson",
felt: 1,
cdi: 4.2999999999999998,
mmi: 4.4779999999999998,
alert: "green",
status: "reviewed",
tsunami: 1,
sig: 483,
net: "us",
code: "70004psn",
ids: ",us70004psn,",
sources: ",us,",
types: ",dyfi,geoserve,losspager,moment-tensor,origin,phase-data,shakemap,",
nst: null,
dmin: 3.2029999999999998,
rms: 0.89000000000000001,
gap: 28,
magType: "mww",
type: "earthquake",
title: "M 5.6 - 23km NNW of Kandrian, Papua New Guinea"
},
geometry: { type: "Point", coordinates: [149.5069, -6.0086000000000004, 59.789999999999999] },
id: "us70004psn"
},
{
type: "Feature",
properties: {
mag: 5.0999999999999996,
place: "Easter Island region",
time: 1563647034336,
updated: 1563892918040,
tz: -420,
url: "https://earthquake.usgs.gov/earthquakes/eventpage/us70004pra",
detail: "https://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us70004pra&format=geojson",
felt: null,
cdi: null,
mmi: null,
alert: null,
status: "reviewed",
tsunami: 0,
sig: 400,
net: "us",
code: "70004pra",
ids: ",us70004pra,",
sources: ",us,",
types: ",geoserve,origin,phase-data,",
nst: null,
dmin: 2.7559999999999998,
rms: 0.71999999999999997,
gap: 118,
magType: "mb",
type: "earthquake",
title: "M 5.1 - Easter Island region"
},
geometry: { type: "Point", coordinates: [-111.38379999999999, -29.3232, 10] },
id: "us70004pra"
},
{
type: "Feature",
properties: {
mag: 5.0999999999999996,
place: "136km ESE of Pangai, Tonga",
time: 1563635789233,
updated: 1563636880040,
tz: -720,
url: "https://earthquake.usgs.gov/earthquakes/eventpage/us70004pp5",
detail: "https://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us70004pp5&format=geojson",
felt: null,
cdi: null,
mmi: null,
alert: null,
status: "reviewed",
tsunami: 0,
sig: 400,
net: "us",
code: "70004pp5",
ids: ",us70004pp5,",
sources: ",us,",
types: ",geoserve,origin,phase-data,",
nst: null,
dmin: 3.2749999999999999,
rms: 1.3100000000000001,
gap: 116,
magType: "mww",
type: "earthquake",
title: "M 5.1 - 136km ESE of Pangai, Tonga"
},
geometry: { type: "Point", coordinates: [-173.15700000000001, -20.294899999999998, 10] },
id: "us70004pp5"
}
],
bbox: [-178.1173, -31.1748, 10, 149.5069, -6.0086, 59.79]
};
var i = 0;
document.writeln("<div>");
for (i = 0; i < object.features.length; i++) {
var timestamp = object.features[i].properties.time / 1000;
date = new Date(timestamp * 1000);
dateString = date.toUTCString();
var today = date;
today.setHours(today.getHours() + 4);
// maps
document.writeln("<div class='list'>");
document.writeln("<div>" + object.features[i].properties.mag + " Mag</div>");
document.writeln("</div>");
}
document.writeln("</div>");
var map = L.map("map").setView([-31.174800000000001, -178.1173], 2);
// load a tile layer
L.tileLayer(
"https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}",
{
attribution:
"Tiles © Esri — Source: Esri, DeLorme, NAVTEQ, USGS, Intermap, iPC, NRCAN, Esri Japan, METI, Esri China (Hong Kong), Esri (Thailand), TomTom, 2012",
maxZoom: 18
}
).addTo(map);
// load GeoJSON from an external file
$.getJSON(
"https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2019-07-20&endtime=2019-07-21&minmagnitude=5",
function(data) {
var geojsonMarkerOptions = {
opacity: 0.8,
fillOpacity: 0.6
};
// color indication by magnitude
geoLayer = L.geoJson(data, {
// popup div content
onEachFeature: function(feature, layer) {
// variable1 = L.marker([-31.174800000000001,-178.1173]).bindPopup('The html content').addTo(map);
var popupText =
"<b>Magnitude:</b> " +
feature.properties.mag +
"<br><b>Location:</b> " +
feature.properties.place;
layer.bindPopup(popupText, {
closeButton: true,
offset: L.point(0, -20)
});
layer.on("click", function() {
layer.openPopup();
});
},
style: function(feature) {
var mag = feature.properties.mag;
if (mag >= 4.0) {
return { color: "red" };
} else if (mag >= 3.0) {
return { color: "orange" };
} else if (mag >= 2.0) {
return { color: "yellow" };
} else {
return { color: "black" };
}
},
// add GeoJSON layer to the map once the file is loaded
pointToLayer: function(feature, latlng) {
return L.circleMarker(latlng, geojsonMarkerOptions);
}
}).addTo(map);
}
);
</script>
</body>
</html>
Here is an example of a possible solution using es6:
create for instance a div which will hold the anchor tags to be added dynamically:
<div id="anchors"></div>
Now in the js file:
let markersArray = {}; // create the associative array
let magsArray = {}; // here hold the ids that correspond to the mags
// load GeoJSON from an external file
$.getJSON("https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2019-07-20&endtime=2019-07-21&minmagnitude=5", data => {
// color indication by magnitude
L.geoJson(data, {
// add GeoJSON layer to the map once the file is loaded
pointToLayer: function(feature, latlng) {
const mag = feature.properties.mag;
const geojsonMarkerOptions = {
opacity: 0.8,
fillOpacity: 0.6,
// here define the style using ternary operators for circles
color: mag >= 4.0 ? 'red' : mag >= 3.0 ? 'orange' : mag >= 2.0 ? 'yellow' : 'black'
};
// here store the circle markers in the array
markersArray[feature.id] = L.circleMarker(latlng, geojsonMarkerOptions)
.addTo(map)
.bindPopup(
`<b>Magnitude:</b> " ${feature.properties.mag}
<br><b>Location:</b> ${feature.properties.place}`, {
closeButton: true,
offset: L.point(0, -20)
});
// here record the mags
magsArray[feature.id] = feature.properties.mag;
return L.circleMarker(latlng, geojsonMarkerOptions);
},
})
// add dynamically anchor tags
let markup = '';
for (let i in markersArray) {
markup += `<b>${magsArray[i]} Mag</b><br/>`;
}
document.getElementById('anchors').innerHTML = markup;
});
Last but not least I do not see the reason of fetching the data using the API and both have it also as a constant variable in your file.
Demo
i have to change the color or borders of buildings on click.
HTML & JS
Like the examples to hover countries, but with click and not countries -> buildings.
If it's easier with another plugin, please say so. 3D is not a 'must have'.
My Code:
<script>
mapboxgl.accessToken = 'hidden';
var map = new mapboxgl.Map({
style: 'mapbox://styles/mapbox/light-v9',
center: [7.3337859, 50.8403206],
zoom: 19.8,
pitch: 60,
bearing: -70,
hash: true,
container: 'map'
});
// The 'building' layer in the mapbox-streets vector source contains building-height
// data from OpenStreetMap.
map.on('load', function() {
// Insert the layer beneath any symbol layer.
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',
'filter': ['==', 'extrude', 'true'],
'type': 'fill-extrusion',
'minzoom': 15,
'paint': {
'fill-extrusion-color': '#aaa',
// use an 'interpolate' expression to add a smooth transition effect to the
// buildings as the user zooms in
'fill-extrusion-height': [
"interpolate", ["linear"], ["zoom"],
15, 0,
15.05, ["get", "height"]
],
'fill-extrusion-base': [
"interpolate", ["linear"], ["zoom"],
15, 0,
15.05, ["get", "min_height"]
],
'fill-extrusion-opacity': .6
}
}, labelLayerId);
map.on('click', '3d-buildings', function(e) {
console.log(e.features[0]);
//map.setPaintProperty('3d-buildings', 'fill-extrude-color', '#FF0000');
map.setPaintProperty('3d-buildings', 'fill-color', '#faafee');
});
});
Thanks :)
You need to add a layer on which to display the selected buildings. For example:
map.addSource('currentBuildings', {
type: 'geojson',
data: {
"type": "FeatureCollection",
"features": []
}
});
map.addLayer({
"id": "highlight",
"source": "currentBuildings",
'type': 'line',
'minzoom': 15,
'paint': {
'line-color': '#f00',
'line-width': 3
}
}, labelLayerId);
map.on('click', '3d-buildings', function(e) {
map.getSource('currentBuildings').setData({
"type": "FeatureCollection",
"features": e.features[0]]
});
});
[ https://jsfiddle.net/o50vy8jc/ ]
This is my json response from URL:
{
"geometry": {
"type": "Point",
"coordinates": [
-1.480921,
52.979698
],
"Timestamp": "2017-07-09T09:21:30",
"GatewayID": 193,
"Speed": 94.9,
"Heading": 157
},
"type": "Feature",
"properties": {}
}
This is my js file:
var map = L.map('map', {
'center': [0, 0],
'zoom': 0,
'layers': [
L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
'attribution': 'Map data © OpenStreetMap contributors'
})
]
});
var geojsonMarkerOptions = {
radius: 18,
fillColor: "#ff7800",
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
};
var realtime = L.realtime({
url: 'http://127.0.0.1:8000/mongo/getgpsdata/',
crossOrigin: true,
type: 'json'
}, {
interval: 3 * 1000,
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng)
}
}).addTo(map);
realtime.on('layeradd', function(e) {
var coordPart = function(v, dirs) {
return dirs.charAt(v >= 0 ? 0 : 1) +
(Math.round(Math.abs(v) * 100) / 100).toString();
},
popupContent = function(fId) {
var feature = e.features[fId],
c1 = feature.geometry.Speed
c2=feature.geometry.Timestamp
c = feature.geometry.coordinates;
return '<b>coord: </b>' +c + '<br><b>Speed:</b> '+c1 + '<br><b>Time: </b>' + c2;
},
bindFeaturePopup = function(fId) {
realtime.getLayer(fId).bindPopup(popupContent(fId));
},
updateFeaturePopup = function(fId) {
realtime.getLayer(fId).getPopup().setContent(popupContent(fId));
};
map.fitBounds(realtime.getBounds(), {maxZoom: 30});
Object.keys(e.enter).forEach(bindFeaturePopup);
Object.keys(e.update).forEach(updateFeaturePopup);
});
It works perfectly fine but it wont show the popups, but if i give 'update' in place of 'layeradd' then it gives me the popups but the historical data is lost as it gets updated every time.
Any help would be great, Thanks!
Add bindPopup while returning the Marker, this worked for me.
return L.circleMarker(latlng).bindPopup("your content")