douduiwei2831
2014-01-03 21:04
浏览 94
已采纳

使用传单js的动态PHP geo json示例

Greeting all. Here is an example on the Leaflet main site of some GeoJson that is static. I want to make this more dynamic by say swapping out the density node data for something coming from a database (DB). Here is some code showing my attempt at mixing the static code with data retrieved from a DB done in PHP.

$jsonStr = "{\"type\":\"FeatureCollection\",\"features\":[";
    foreach($data as $info){
        if($counter == $count-1){
            $jsonStr .= "
                {\"type\":\"Feature\",\"id\":\"".$info["site_state"]."\",\"properties\":
                    {
                        \"name\":\"".$info["state_dscr"]."\",\"density\":".$info["coalesce"]."
                    }
                }";
        }else{
            $jsonStr .= "
                {\"type\":\"Feature\",\"id\":\"".$info["site_state"]."\",\"properties\":
                    {
                        \"name\":\"".$info["state_dscr"]."\",\"density\":".$info["coalesce"]."
                    }
                },";
        }   
        $counter++;
    }

$jsonStr .= "]}";

$test = json_decode($jsonStr);
//Validate the JSON
if($test === NULL){
    error_log("There is an issue with your json.");
}else{
    header('Content-Type: application/json');
    echo $jsonStr;
}

The above code is run via an D3 json() call like so:

d3.json("js/statesDataJson.php", function(vioData) { ...}

within another js file. And yes my json is missing the state coordinates, which is why i cannot reproduce the choropleth layer found in the example on the leaflet tutorial site (See below link).

This is my attempt at making this example found here more dynamic. I thought i might be able to mix the data from two sources and using the "desnity" node data from one source and use the "geometry" node from the other to build the state layer. That is where i am having problems.
My initial idea is to set up a table in a DB for the geo JSON and continue with my above example of dynamically replicating this.

I am wondering if i am using a canon ball to kill a roach and there is there is a more efficient strategy or solution. Or is the database the only way to dynamically rebuild my json? For example would any advocate trying to parse the json file and edit the density node? Seems ... asinine but i am open to suggestions.

Thank you

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • donglin6109 2014-01-03 21:14
    已采纳

    What you are building there, those Feature and FeatureCollection, are GeoJSON. You can find/write a library that takes an array and turns in into GeoJSON. GeoJSON website has a PHP implementation listed under Libraries section. You can find it here inside GeoJSON.class.php. It doesn't have any documentation, but comments are there and the code is fairly simple, you should be able to use the class, and form your own GeoJSON and return it from your server.

    评论
    解决 无用
    打赏 举报
  • 查看更多回答(2条)

相关推荐 更多相似问题