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

时间:2011-07-06 05:32:14

标签: openlayers json geojson

我需要将Json字符串更改为Geojson格式。现在我正在使用Json_encode()函数将sql查询结果转换为json字符串(如此链接JSON encode MySQL results中所示)。
我想通过openlayers使这个geojson字符串可读  我怎样才能将json _encode用于此目的? 或者我可以使用不同的功能吗? 提前谢谢。

3 个答案:

答案 0 :(得分:1)

(我假设您使用的是PHP)。

如果您将空间数据提取为WKT(1),则可以使用PHP版本的mapfish中的GeoJSON类(2)(此类可以使用没有mapfish)。

你必须为此编写自己的适配器。

HTH,

答案 1 :(得分:1)

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 += "]}"

答案 2 :(得分:1)

过去几周我实际上一直在研究这个问题。需要注意的重要事项:我没有使用地理空间数据库,只是正常的存储空间(确切地说是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”功能,以便我快速构建功能。另请注意,我几乎将整行添加到属性对象中。 Overkill / Redundant,但代码更简单。

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