Mapbox issue with parsing json data for heatmap - javascript

My code is this
heat = L.heatLayer([], { maxZoom: 12 }).addTo(map);
$.getJSON("js/example-single.geojson", function(data) {
var geojsosn = L.geoJson(data, {
onEachFeature: function (feature, layer) {
console.log(feature.geometry.coordinates[0] ,feature.geometry.coordinates[1]);
heat.addLatLng(feature.geometry.coordinates[0], feature.geometry.coordinates[1]);
}
});
but am getting an error "Uncaught TypeError: Cannot read property 'lat' of undefined"
please tell how to fix this, if my code is wrong somebody show me how to parse json data for heat map in mapbox
my json data is
{ "type": "FeatureCollection",
"features": [
{ "type": "Feature",
"geometry": {"type": "Point", "coordinates": [13.353323936462402, 38.11200434622822]},
"properties": {"marker-color": "#000"}
}
]
}

addLatLng probably expects L.latLng objects or something that has lat & lng properties.
var heat = L.heatLayer([], { maxZoom: 12 }).addTo(map);
$.getJSON('js/example-single.geojson', function(data) {
var geojson = L.geoJson(data, {
onEachFeature: function(feature, layer) {
feature.geometry.coordinates.forEach(function(p) {
heat.addLatLng(L.latLng(p[0], p[1]));
});
}
});
});

Related

GEOjson not displaying in my map openlayers

I want to display geojson data in my map openLayers but my data didn't show and the map doesn't even display. I work with openLayers 5.
I have an api (in node.js) which allows to extract the data in my database.
I have a file (script.js) which allows to display the map, recover the data sent by the api and display the data on the map.
In script.js :
I create a new vectorLayer which contain the style of the geojson :
var foncier2 = new VectorLayer({
source:source,
style: function (feature, res) {
property = feature.get("nature");
return new Style({
stroke: new Stroke({
color: [40, 40, 40, 1],
width: 0.3
}),
fill: new Fill({
color: couleur(property)
})
})
},});
I request on my API to recover the data with the help of a callback :
`
function loadJSON(callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
console.log(this.responseText);
callback(this.responseText);
}
};
xhr.open("GET", "adressIP:port/endpoint", true);
// xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(null);
}`
Then I create a function which transform the data into json then into GEOjson :
var myData = JSON.parse(data);
var geojsonObject = {
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "EPSG:4326" }},
"features": [
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates":myData[2].geom
}
}
]};
Finally i display the data :
foncier2.getSource().clear();
foncier2.getSource().addFeatures(foncier2.getSource().getFormat().readFeatures(geojsonObject, {
dataProjection: 'EPSG:4326',
defaultFeatureProjection: 'EPSG:3857',
}));
foncier2.getSource().refresh();
foncier2.getSource().changed();
map.getView().fit(foncier2.getSource().getExtent());
But
nothing displays on my map and I don't have error in my console log.
Thank you for helping me
PS : ( I managed to recover the data,it looks like that and the coordinates )
You are setting coordinates to the geometry (which your screenshot shows is multipolygon) instead of the geometry's coordinates and not updating the type. Try this:
var geojsonObject = {
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "EPSG:4326" }},
"features": [
{
"type": "Feature",
"geometry": {
"type": JSON.parse(myData[2].geom).type,
"coordinates": JSON.parse(myData[2].geom).coordinates
}
}
]};

Parsing JSON API result and loading in to Leaflet

I am trying to take the JSON from an API call, parse it in to a GeoJSON array (just taking the lat, long and name variable) and then load it in to a Leaflet map.
I am getting no errors in the console. The geojson is loading in to the map but it is empty. When i query it (console.log(geojson) it appears empty. For some reason my function is failing to correctly parse in to the geojson.
var map1 = L.map('map').setView([52.599043, -1.325812], 6);
var OpenStreetMap_Mapnik = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© OpenStreetMap'
}).addTo(map1);
var ports = $.ajax({
url:"API_URL",
dataType: "json",
success: console.log("County data successfully loaded."),
})
var geojson = {
type: "FeatureCollection",
features: [],
};
for (var i in ports.data) {
geojson.features.push({
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [ports.data[i].longitude, ports.data[i].latitude]
},
"properties": {
"stationName": ports.data[i].port_name
}
});
}
L.geoJSON(geojson).addTo(map1);
Following Andreas's comment I looked in to Asynchronous AJAX.
I ended up restructuring my code to ensure that the processing of the response was done after the ajax call was completed:
I nested the processing of API response in a function that used the output from the API call. The API call has a function that runs when it's successful that passes the response to the processing function.
function callback1(response) {
var geojson = {
type: "FeatureCollection",
features: [],
};
for (var i in response.data) {
geojson.features.push({
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [response.data[i].longitude, response.data[i].latitude]
},
"properties": {
"stationName": response.data[i].port_name
}
})};
L.geoJSON(geojson, {onEachFeature:Ports_Popup}).addTo(map1);
console.log(response);
};
$.ajax({
url:"https://statistics-api.dft.gov.uk/api/ports?filter[country]=scotland",
dataType: "json",
success: function(response){
callback1(response)
}})

Leaflet.draw geojson layer edit

As you see in this fiddle , I have a polygon like this:
var data = [{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[2.504410743713379,44.28253972334941],
[2.504410743713379,44.28929846767132],
[2.5168561935424805,44.28929846767132],
[2.5168561935424805,44.28253972334941],
[2.504410743713379,44.28253972334941]
]
]
}}]
When I want to add it to my featureGroup drawnItems I use:
var geojsonLayer = L.geoJson(data);
geojsonLayer.getLayers()[0].addTo(drawnItems);
Then I decide to edit polygon I can't move it because the central move handler does not appear, But when I draw new polygon using the toolbar I have move handler.
Could you please help me?
how can I add my polygon to have move handler?
Do something like this to add every Geojson layer to drawnItems:
var geeoojson = L.geoJSON(JSON.parse(data), {
onEachFeature: function (feature, layer) {
layer.addTo(drawnItems);
}
}).addTo(map)

GeoJSON Point name & description not displayed when using Google Map API V3

I am starting to use the Google Map Javascript API V3 and wish to display markers on a map, using GeoJSON. My GeoJSON is as follows:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [153.236112, -27.779627]
},
"properties": {
"name": "[153.236112, -27.779627]",
"description": "Timestamp: 16:37:16.293"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [153.230447, -27.777501]
},
"properties": {
"name": "[153.230447, -27.777501]",
"description": "Timestamp: 16:37:26.298"
}
}
]
}
And my JavaScript code to load the GeoJSON:
var map;
var marker;
function initialize() {
// Create a simple map.
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 14,
center: ${lastPosition}
});
// Load the associated GeoJSON
var url = 'fieldDataGeoJSON';
url += '?deviceId=' + deviceId + '&fieldId=' + fieldId;
map.data.loadGeoJson(url);
}
google.maps.event.addDomListener(window, 'load', initialize);
Note: the URL "fieldDataGeoJSON.." returns the GeoJSON, as you might have already figured out.
This works well: the markers are shown on the map, at the good location. But the fields "name" and "description" present in the GeoJSON are not linked to the markers, meaning that they are not displayed when I click on the marker.
I guess that the first question would be: "Is it supposed to be supported?". If not, does it mean that I have to parse the GeoJSON to add the names and descriptions? Do you have any hints on how to achieve this?
Thank you in advance for your help!
Normal Google Maps Javascript API v3 event listeners work, as do normal infowindows.
var map;
var infowindow = new google.maps.InfoWindow();
function initialize() {
// Create a simple map.
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 14,
center: new google.maps.LatLng(-27.779627,153.236112)
});
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Load the associated GeoJSON
var url = 'http://www.geocodezip.com/fieldDataGeoJSON.txt';
map.data.loadGeoJson(url);
// Set event listener for each feature.
map.data.addListener('click', function(event) {
infowindow.setContent(event.feature.getProperty('name')+"<br>"+event.feature.getProperty('description'));
infowindow.setPosition(event.latLng);
infowindow.setOptions({pixelOffset: new google.maps.Size(0,-34)});
infowindow.open(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
working example

leaflet map: make polygon clickable

I managed to create map with leaflet.js & jQuery mobile.
Now I need to get rid of jQuery mobile and just use jQuery instead.
Everything works just fine, but I can't click the polygons which I draw on the map anymore. It worked with jQuery mobile before.
Any hints?
here is my simplified code:
var map = L.map('map', {
zoomControl: false
});
L.tileLayer('http://{s}.tile.cloudmade.com/**apikey***/997/256/{z}/{x}/{y}.png', {
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © CloudMade',
maxZoom: 18
}).addTo(map);
For the polygons:
var geojsonFeature = { "type": "Polygon","coordinates": value.polygon};
var polycolor = getGebColor(value.geb_nr);
var geojsonStyle = {"color": polycolor};
polygons[i] = L.geoJson(geojsonFeature, {style: geojsonStyle}).addTo(map);
// make clickable
polygons[i].on('click', function(e) {
if (lastMarker) {
map.removeLayer(lastMarker);
}
var url = "http://*****/tugetherMap.php?callback=&id="+value.id+"&type=B";
markers[i] = L.marker([value.point[1], value.point[0]]).addTo(map);
gebName = value.nameLang;
markers[i].bindPopup("<a class='gebOnMap' href='gebaeude.html' >"+gebName+"</a>").openPopup();
lastMarker = markers[i];
});
the polygons[i].on('click',...) is the part which does not work anymore. It works for map.on('click',...)
You need to bind each of your polygons to a click event handler, like so.
L.geoJson(geojsonFeature, {
onEachFeature: function(feature, layer) {
layer.on('click', function(e) {
// Do whatever you want here, when the polygon is clicked.
});
}
}).addTo(map);
Had a issue with this and solved it with the following
function onEachFeature(feature, layer) {
// Do all your popups and other binding in here
// does this feature have a property named popupContent?
if (feature.properties && feature.properties.popupContent) {
layer.bindPopup(feature.properties.popupContent);
}
}
var geojsonFeature = {
"type": "Feature",
"properties": {
"name": "Coors Field",
"amenity": "Baseball Stadium",
"popupContent": "This is where the Rockies play!"
},
"geometry": {
"type": "Point",
"coordinates": [-104.99404, 39.75621]
}
};
L.geoJson(geojsonFeature, {
onEachFeature: onEachFeature
}).addTo(map);
In your code I guess it would be
polygons[i] = L.geoJson(geojsonFeature, {onEachFeature: onEachFeature,
style: geojsonStyle}).addTo(map);
function onEachFeature(feature, layer) {
// Some jazz and magic you need to do with your layer and feature objects
}
The solution for me was to downgrade Leaflet to 0.7.3 or upgrade to 1.0-beta2 (latest version at the time of writing).

Categories