让我的 Json 字符串解析 openlayers.format.geojson

发布于 2024-11-18 13:13:19 字数 282 浏览 3 评论 0原文

我需要将 Json 字符串更改为 Geojson 格式。现在我正在使用 Json_encode() 函数将 sql 查询结果转换为 json 字符串(如此链接 JSON对 MySQL 结果进行编码)。
我想让 openlayers 可以读取这个 geojson 字符串。
我如何使用 json _encode 来实现此目的? 或者我可以使用不同的功能吗? 提前致谢。

i need to change a Json string into Geojson format. right now i am using Json_encode() function to convert sql query result into json string (as given in this link JSON encode MySQL results).
i want to make this geojson string readable by openlayers.
how can i use json _encode for this purpose ?
or is there a different function which i can use for this?
thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

彩扇题诗 2024-11-25 13:13:19

GeoJSON 格式相当简单,因此我将继续循环 SQL 查询返回的所有原始数据,并手动构建 GeoJSON 格式的字符串。然后,将此字符串从服务器端代码传递到客户端,在客户端将其解析为 JavaScript 对象,以便 OpenLayers 可以使用它。

这是我不久前用 Ruby 完成的示例。希望您能明白这一点,并能在 PHP 中做同样的事情:

    json = "{ \"type\": \"FeatureCollection\", \"features\": ["

    layer.get_feature_count.times do |i|
        feature = layer.get_feature(i)
        json += "{\"type\":\"Feature\", \"id\":" + feature.get_fid.to_s + ", \"properties\": {"

        feature_defn = layer.get_layer_defn

        feature_defn.get_field_count.times do |j|
            field = feature_defn.get_field_defn(j)      
            json += "\"" + field.get_name_ref + "\":" + "\"" + feature.get_field(j).to_s + "\""

            if j+1 < feature_defn.get_field_count
                json += ", "
            end
        end

        json += "}, " 
        #end of properties

        geom = feature.get_geometry_ref 
        json += "\"geometry\":" + geom.export_to_json
        #end of geometry

        json += "}"

        if i+1 < layer.get_feature_count
            json += ", "
        end 
    end

    json += "]}"

GeoJSON format is fairly simple so I would go ahead and loop through all raw data that your SQL query returns and build a string in GeoJSON format manually. Then you pass this string from you server side code to the client where you parse it to javascript object so that OpenLayers can consume it.

Here's example in Ruby I've done a while ago. Hope you get the idea and can do the same in PHP:

    json = "{ \"type\": \"FeatureCollection\", \"features\": ["

    layer.get_feature_count.times do |i|
        feature = layer.get_feature(i)
        json += "{\"type\":\"Feature\", \"id\":" + feature.get_fid.to_s + ", \"properties\": {"

        feature_defn = layer.get_layer_defn

        feature_defn.get_field_count.times do |j|
            field = feature_defn.get_field_defn(j)      
            json += "\"" + field.get_name_ref + "\":" + "\"" + feature.get_field(j).to_s + "\""

            if j+1 < feature_defn.get_field_count
                json += ", "
            end
        end

        json += "}, " 
        #end of properties

        geom = feature.get_geometry_ref 
        json += "\"geometry\":" + geom.export_to_json
        #end of geometry

        json += "}"

        if i+1 < layer.get_feature_count
            json += ", "
        end 
    end

    json += "]}"
櫻之舞 2024-11-25 13:13:19

(我从你的帖子中假设你正在使用 PHP)。

如果您以 WKT (1) 的形式获取空间数据,则可以使用 PHP 版本的 mapfish 中的 GeoJSON 类(2)(该类可以在不使用 mapfish 的情况下使用)。

您只需为此编写自己的适配器即可。

HTH,

(I assume from your post that you're using PHP).

If you fetch your spatial data as WKT (1), you can use the GeoJSON class(2) from the PHP version of mapfish ( this class could be used w/o mapfish ).

You'll just have to write your own adapter for this.

HTH,

像你 2024-11-25 13:13:19

事实上,过去几周我一直在研究同样的问题。需要注意的是:我没有使用地理空间数据库,只是使用普通的存储(确切地说是 MySQL)。

以下是我完成它的方法(没有混乱的 concat 语句):

SQL 表描述:

CREATE TABLE IF NOT EXISTS `conditions` (
  `conditionsID` int(10) unsigned NOT NULL auto_increment,
  `ICAO` varchar(4) default NULL,
  `LOCATION` varchar(50) default NULL,
  `LATITUDE` float default NULL,
  `LONGITUDE` float default NULL,
  `TEMPERATURE` float default NULL,
  `TEMPERATURE_F` float default NULL,
  `TEMPERATURE_C` float default NULL,
  `FEELS_LIKE` float default NULL,  
  PRIMARY KEY  (`conditionsID`),
  KEY `ICAO` (`ICAO`),
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=56274738 ;

然后我可以使用 json_encode PHP 库(首先在 5.2 中可用,5.3 中有更好的选项)从 PHP 对象编码 json 对象。不再使用字符串,而是可以使用伪对象(我更喜欢数组,易于动态管理)。 5.3 还提供了漂亮打印的选项。

我的 PHP 服务器代码:

$feature_collection = array();
$feature_collection['type'] = "FeatureCollection";
$feature_collection['features'] = array();

$con = mysql_connect($DB_URI, $DB_USER, $DB_PASS);
if (!$con) {
    $errorMessage = "Error: Could not connect to data database.  Error: " . mysql_error();
} else {
    mysql_select_db("data", $con);
    $result = mysql_query("SELECT * FROM `conditions` WHERE LATITUDE > $LAT AND LONGITUDE > $LON GROUP BY LOCATION;");

    while ($row = mysql_fetch_assoc($result)) {
        $feature_collection['features'][] = createFeature($row['conditionsID'],
                                                          $row['LATITUDE'],
                                                          $row['LONGITUDE'],
                                                          $row);
    }
}


echo json_encode($feature_collection);

function createFeature($ID, $lat, $lon, $data)
{
    unset($data["LATITUDE"]);
    unset($data["LONGITUDE"]);
    $feature = array();
    $feature["type"] = "Feature";
    $feature["id"] = $ID;

    $feature["geometry"] = array();
    $feature["geometry"]["type"] = "Point";
    $feature["geometry"]["coordinates"] = array($lon+0, $lat+0);

    $feature["properties"] = $data;
    $feature["properties"]["visible"] = "true";

    return $feature;
}

请注意“FeatureCreate”函数,它允许我快速构建功能。另请注意,我将几乎整行添加到属性对象中。过度杀伤/冗余,但可以使代码更简单。

希望这个片段会有所帮助。它完成了我的工作(我很乐意听取其他人的建议)。

I've actually have been working on this same issue over the past few weeks. Important to note: I'm not using a geospatial database, just normal ol' storage for me (MySQL to be exact).

Here is how I accomplished it (without the messy concat statements):

SQL Table Description:

CREATE TABLE IF NOT EXISTS `conditions` (
  `conditionsID` int(10) unsigned NOT NULL auto_increment,
  `ICAO` varchar(4) default NULL,
  `LOCATION` varchar(50) default NULL,
  `LATITUDE` float default NULL,
  `LONGITUDE` float default NULL,
  `TEMPERATURE` float default NULL,
  `TEMPERATURE_F` float default NULL,
  `TEMPERATURE_C` float default NULL,
  `FEELS_LIKE` float default NULL,  
  PRIMARY KEY  (`conditionsID`),
  KEY `ICAO` (`ICAO`),
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=56274738 ;

I can then use the json_encode PHP library (first available in 5.2, better options for 5.3) to encode a json object from a PHP object. No more working with strings, instead I can work with pseudo-objects (I prefer arrays, easy to manage on the fly). 5.3 brings the option to pretty print as well.

My PHP server code:

$feature_collection = array();
$feature_collection['type'] = "FeatureCollection";
$feature_collection['features'] = array();

$con = mysql_connect($DB_URI, $DB_USER, $DB_PASS);
if (!$con) {
    $errorMessage = "Error: Could not connect to data database.  Error: " . mysql_error();
} else {
    mysql_select_db("data", $con);
    $result = mysql_query("SELECT * FROM `conditions` WHERE LATITUDE > $LAT AND LONGITUDE > $LON GROUP BY LOCATION;");

    while ($row = mysql_fetch_assoc($result)) {
        $feature_collection['features'][] = createFeature($row['conditionsID'],
                                                          $row['LATITUDE'],
                                                          $row['LONGITUDE'],
                                                          $row);
    }
}


echo json_encode($feature_collection);

function createFeature($ID, $lat, $lon, $data)
{
    unset($data["LATITUDE"]);
    unset($data["LONGITUDE"]);
    $feature = array();
    $feature["type"] = "Feature";
    $feature["id"] = $ID;

    $feature["geometry"] = array();
    $feature["geometry"]["type"] = "Point";
    $feature["geometry"]["coordinates"] = array($lon+0, $lat+0);

    $feature["properties"] = $data;
    $feature["properties"]["visible"] = "true";

    return $feature;
}

Notice the "FeatureCreate" function to allow me to build a feature quickly. Also note I add almost the entire row into the properties object. Overkill/Redundant, but makes for simpler code.

Hopefully this snippet will help. It does my job (and I'd be happy to listen to others suggestions).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文