在JSON数组中显示D3中的坐标



我从PHP中获得JSON响应坐标如下

{"All":[{"longitude":"36.8948669","name":" Manyanja Rd, Nairobi, Kenya","latitude":"-1.2890965","userID":"1"}, ...]}

我之后通过JavaScript加载它,如下所示:

$.ajax({
url : "http://xxx.xxx.xxx/GetLocations.php",
dataType : "json",
data :"",
success : 
function (data){
//populate map is the function that I pass the coordinates to d3 to be shown 
 //when i console.log(data), its showing me the json so I am sure the data is there
populate_map(data)
}
});

这是功能populate_map。

function populate_map(pos_data){
    console.log(pos_data.All[0]);
    var width = 700;
var height = 580;
var svg = d3.select( "body" )
    .append( "svg" )
    .attr( "width", width )
    .attr( "height", height );
var g = svg.append( "g" );
var albersProjection = d3.geo.albers()
    .scale( 190000 )
    .rotate( [71.057,0] )
    .center( [0, 42.313] )
    .translate( [width/2,height/2] );
var geoPath = d3.geo.path()
    .projection( albersProjection );


var projection = d3.geo.mercator()
.center([36.8, -1.3])
.scale([60000])
.translate([width/2, height/2]);
var nairobipathing = d3.geo.path().projection(projection);
g.selectAll( "path" )
    .data( data.geometries )
    .enter()
    .append( "path" )
    .attr( "fill", "#ccc" )
    .attr( "stroke", "#333")
    .attr( "d", nairobipathing );

      svg.selectAll("circles.points")
        .data(pos_data)
        .enter()
        .append("circle")
        .attr("r",5)
        .attr("transform", function(d) {return "translate("  d.All.longitude+","+d.All.latitude ")";});
}

问题在于,它没有在内罗毕地图上显示我最初的任何坐标,但是当我安装时。

最后一个SVG是我用这些坐标来填充地图的

,但它不起作用,也不显示地图中的任何坐标。

请帮助我向我展示问题在哪里

首先,您似乎正在使用两个预测,如果您删除了以北美北美海岸为中心的Albers投射的参考。

第二,您应该传递给出的数据对象而不是数据对象的数据对象中的点数。

第三,转换中使用的值必须在SVG坐标空间中而不是地理坐标空间中。在您的示例中,您使用 d.all.longitude d.all.latitude 而无需应用投影。您需要使用投影([经度,纬度])以获取圆的SVG坐标。这将在SVG坐标空间中返回坐标[x,y](如果需要,您可以分别提取x和y坐标。

基于第二和第三点,您的观点可以附加到以下内容之类的东西:

     svg.selectAll(".points")
            .data(pos_data.All)
            .enter()
            .append("circle")
            .attr("class","points")
            .attr("r", 5 )
            .attr("stroke","orange")
            .attr("transform", function(d) {return "translate(" + projection([d.longitude,d.latitude]) + ")";})

另外,您可以使用.attr(" cx",x)或.attr(" cy",y)作为点中心而不是翻译:

         svg.selectAll(".points")
            .data(test.All)
            .enter()
            .append("circle")
            .attr("class","points")
            .attr("r", 5 )
            .attr("stroke","orange")
            .attr("cx", function(d) { return projection([d.longitude,d.latitude])[0]; })
            .attr("cy", function(d) { return projection([d.longitude,d.latitude])[1]; })

最新更新