Reputation: 51
I'm getting a lat/lon array with ajax
$.ajax({
type: "POST",
url: '../m/m_share.php',
data: 'zone=' + zone,
dataType: 'json',
success: function(tab) {
var i = 0;
var size = tab.length;
for (i = 0; i < size; i++) {
var lat = tab[i]['lat'];
var lon = tab[i]['lon'];
}
}
The "tab" param is a jscon_encode(array) sent by php of my lat/lon request from db. What I would like to do is creating a geojson such as this one but with my lat/lon datas.
var geojson =
{"name":"NewFeatureType",
"type":"FeatureCollection",
"features":[{"type":"Feature",
"geometry":{"type":"LineString",
"coordinates":[[169.13693,-44.696476,296],[169.134602,-44.69764,295],[169.129983,-44.701164,299]]},
"properties":null}]};
I tried to save the lat/lon in a var
$.ajax({
type: "POST",
url: '../m/m_share.php',
data: 'zone=' + zone,
dataType: 'json',
success: function(tab) {
var i = 0;
var size = tab.length;
for (i = 0; i < size; i++) {
var lat = tab[i]['lat'];
var lon = tab[i]['lon'];
if(i===size){
coord = coord+'['+lat+','+lon+']';
alert(coord);
}
else{
coord = coord+'['+lat+','+lon+']'+',';
}
}
}
});
And then replace the lat/lon in the geoJson with my coord var but it seems that leaflet does not like it "Invalid LatLng object: (NaN, Nan)".
Upvotes: 4
Views: 13285
Reputation: 113
The approach mentioned by Pedro Estrada is correct. But there is a slight correction required.
GeoJson standard requires geographical points with (longitude,latitude) convention.
var gj = {
"name":"MyFeatureType",
"type":"FeatureCollection",
"features":[]
};
Push a new feature object
gj.features.push({ "type": "Feature","geometry": {"type": "LineString","coordinates": []},"properties": null });
Add a coordinate to newly pushed object:
lon=20;
lat=10;
gj.features[0].geometry.coordinates.push([lon,lat]);
Upvotes: 7
Reputation: 2404
Create a geojson object variable.
var geojson = {
"name":"NewFeatureType",
"type":"FeatureCollection",
"features":[{
"type":"Feature",
"geometry":{
"type":"LineString",
"coordinates":[]
},
"properties":null
}]
};
then you do pushing into coordinates array
geojson.features[0].geometry.coordinates.push([lat, lng]);
Upvotes: 18