无需GeoJsonLayer,如何在Google Map中解析GeoJSON添加点位?
不借助GeoJsonLayer直接解析GeoJSON在Google Map添加点位
当然可以直接解析GeoJSON数据来添加点位,不需要依赖GeoJsonLayer。你可以用普通的JSON解析工具(比如Android自带的JSONObject或者Gson这类库)直接遍历GeoJSON结构,提取所需的坐标信息后创建Marker。
具体实现步骤如下:
- 将GeoJSON字符串(或对应的JSON对象)解析为可操作的JSON结构
- 遍历GeoJSON中的
features数组 - 对每个feature,提取
properties中的general_coordinates字段 - 将该字段按逗号拆分得到纬度和经度,转换为
double类型 - 调用
googleMap.addMarker()创建并添加标记
代码示例(使用Android自带JSONObject)
// 假设objPegsGeoJson是你的GeoJSON字符串或JSONObject JSONObject geoJsonObj; try { // 如果输入是字符串,先转换为JSONObject geoJsonObj = new JSONObject(objPegsGeoJson); JSONArray features = geoJsonObj.getJSONArray("features"); for (int i = 0; i < features.length(); i++) { JSONObject feature = features.getJSONObject(i); JSONObject properties = feature.getJSONObject("properties"); String generalCoordinates = properties.getString("general_coordinates"); // 处理坐标拆分与转换,增加格式校验 String[] latlong = generalCoordinates.split(","); if (latlong.length != 2) { // 跳过格式错误的坐标 continue; } double latitude = Double.parseDouble(latlong[0].trim()); double longitude = Double.parseDouble(latlong[1].trim()); // 添加Marker到地图 Marker mrk = googleMap.addMarker(new MarkerOptions() .position(new LatLng(latitude, longitude)) .anchor(0.5f, 0.5f) ); } } catch (JSONException e) { // 处理JSON解析异常 e.printStackTrace(); } catch (NumberFormatException e) { // 处理经纬度转换异常 e.printStackTrace(); }
补充:如果是标准GeoJSON格式
如果你的GeoJSON采用标准结构(坐标存储在geometry.coordinates下),可以替换坐标提取逻辑为:
JSONObject geometry = feature.getJSONObject("geometry"); JSONArray coordinates = geometry.getJSONArray("coordinates"); // 标准GeoJSON坐标顺序是[经度, 纬度] double longitude = coordinates.getDouble(0); double latitude = coordinates.getDouble(1);
内容的提问来源于stack exchange,提问作者thpererep1
相关产品推荐
相关产品推荐

