使用javascript生成GeoJson

JCh*_*hri 0 javascript php ajax json geojson

我正在使用ajax获得lat/lon数组

$.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'];
        }
    }
Run Code Online (Sandbox Code Playgroud)

"tab"参数是由我发送的来自db的lat/lon请求的php发送的jscon_encode(数组).我想做的是创建一个像这样的geojson但是使用我的lat/lon数据.

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}]};
Run Code Online (Sandbox Code Playgroud)

我试图将lat/lon保存在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+']'+',';

                    }
                }
                }
            });
Run Code Online (Sandbox Code Playgroud)

然后用我的coord var替换geoJson中的lat/lon,但似乎传单不喜欢它"无效的LatLng对象:( NaN,Nan)".

add*_*ddy 6

佩德罗·埃斯特拉达提到的做法是正确的。但需要稍作修正。

GeoJson 标准要求地理点具有(经度、纬度)约定。

var gj = {
    "name":"MyFeatureType",
    "type":"FeatureCollection",
    "features":[]
};
Run Code Online (Sandbox Code Playgroud)

推送新的要素对象

gj.features.push({ "type": "Feature","geometry": {"type": "LineString","coordinates": []},"properties": null });
Run Code Online (Sandbox Code Playgroud)

为新推送的对象添加坐标:

lon=20;
lat=10;
gj.features[0].geometry.coordinates.push([lon,lat]);
Run Code Online (Sandbox Code Playgroud)


Ped*_*ada 5

创建一个geojson对象变量.

var geojson = {
    "name":"NewFeatureType",
    "type":"FeatureCollection",
    "features":[{
        "type":"Feature",
        "geometry":{
            "type":"LineString",
            "coordinates":[]
        },
        "properties":null
    }]
};
Run Code Online (Sandbox Code Playgroud)

然后你推进坐标数组

geojson.features[0].geometry.coordinates.push([lat, lng]);
Run Code Online (Sandbox Code Playgroud)