Using JSON instead of GeoJSON in Leaflet with AJAX - javascript

I'm looking for a way to use JSON instead of GeoJSON in leaflet using AJAX. Using JSON and AJAX are required.
I managed to call JSON file using AJAX. However, now I'm confused how I can use data in JSON to plot markers on map. I'm guessing I can't use L.geoJson().
HTML:
<div id="map" style="width: 800px; height: 500px"></div>
This is the JavaScript file:
var map;
var overlay;
var addPopupsFromLocations = function(locations) {
var popups = new Array();
locations.forEach(function(location){
console.log('creating popup for location ' + location.title);
console.log(location.latitude);
console.log(location.longitude);
}) ;
};
function init() {
var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'examples.map-i86knfo3'
}).addTo(map);
}
$(document).ready(function(){
init();
$.ajax('locations.json', {
dataType: 'json',
success: addPopupsFromLocations,
error: function(xhr, st, et) {
console.warn(et);
}
});
});
This is the JSON file:
[
{
"title": "Weathertop",
"link": "http://en.wikipedia.org/wiki/Weathertop",
"latitude": 51.505,
"longitude": -0.09,
"imageUrl": "assets/img/location-images/Weathertop.jpg"
},
{
"title": "Rivendell",
"link": "http://lotr.wikia.com/wiki/Rivendell",
"latitude": -0.09,
"longitude": 51.505,
"imageUrl": "assets/img/location-images/Rivendell2.jpg"
},
{
"title": "Minas Tirith",
"link": "http://lotr.wikia.com/wiki/Minas_Tirith",
"latitude": 38.78,
"longitude": -77.18,
"imageUrl": "assets/img/location-images/320px-Minas_Tirith.jpg"
}
]
Console:
creating popup for location Weathertop
custom.js (line 7)
51.505
custom.js (line 9)
-0.09
custom.js (line 10)
creating popup for location Rivendell
custom.js (line 7)
-0.09
custom.js (line 9)
51.505
custom.js (line 10)
creating popup for location Minas Tirith
custom.js (line 7)
38.78
custom.js (line 9)
-77.18

I'm looking for a way to use JSON instead of GeoJSON in leaflet using AJAX.
Okay: to review some terms,
JSON is a basic data-interchange format. It doesn't contain anything in particular.
GeoJSON is a subset of JSON that is formatted to be map-friendly and understandable to things like Leaflet.
If you want to use L.geoJson, you need to reformat your data so that it fits the GeoJSON specification. You can do this with basic JavaScript.
var geojsonFormattedLocations = locations.map(function(location) {
return {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [location.longitude, location.latitude]
},
properties: {
location
}
};
});

I know it is a late answer but you definitely can use simple JSON format with Leaflet.
As you say, you receive the JSON with ajax and on success, you run a function that loops each JSON object and for each one, adds a marker on the map. For example:
var response = req.responseText;
var arr = JSON.parse(response);
for (var i=0 ; i<arr.length ; i++) {
L.marker([arr[i].latitude, arr[i].longitude]).addTo(map);
}

Related

Gmap vue save polyline, polygon and load geojson onto google map

I am have a vuejs/nuxtjs application using the gmap-vue package which is a fork of vue-google-maps. I have followed the drawing manager with slot example which is working as shown on the document, good times!
But...
I would like to do two more things
Save the data that I added to the map, how do I access it?
How to load geojson onto the map and then edit it.
Examle below:
More information from further investigation.
I am trying to build up data in the form of geojson
let shapes = [];
for(let shape in this.shapes){
let tmp = {
"type": "Feature",
"properties": {
"id": this.shapes[shape].id || null,
"zIndex": this.shapes[shape].zIndex || null
},
"geometry": {
"type": this.shapes[shape].type,
"coordinates": // where to find shape coordinates?
}
};
shapes.push(tmp)
}
console.log(JSON.stringify(shapes));
displays the following in the console.log
[
{
"type":"Feature",
"properties":{
"id":null,
"zIndex":null
},
"geometry":{
"type":"polygon",
"coordinates": // where to find coordinates?
}
}
]
console.log[this.shapes[shape]];
returns
{__ob__: Observer}
overlay: (...)
type: (...)
How can I access the coordinates?
For anyone else looking for an answer, I hope this helps you out.
const newShapes = [];
this.shapes.forEach((shape) => {
const coords = [];
shape.overlay.latLngs.getArray().forEach((latLng) => {
coords.push([latLng.lat, latLng.lng]);
});
newShapes.push({
type: 'Feature',
geometry: {
type: shape.type,
coordinates: coords,
},
});
});
As shown here: https://diegoazh.github.io/gmap-vue/#getting-a-map-reference
this.$refs.mapRef.$mapPromise.then((map) => {
map.panTo({lat: 1.38, lng: 103.80})
})
is working pretty great.
<gmap-drawing-manager ref="drawingRef">
and
<gmap-drawing-manager :shapes="shapes" ref="drawingRef">
allows to access the same information with this.shapes!

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)
}})

Mapbox issue with parsing json data for heatmap

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]));
});
}
});
});

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