【问题标题】:Google Maps Android JSON Array Polygon谷歌地图 Android JSON 数组多边形
【发布时间】:2015-02-05 01:45:18
【问题描述】:

我正在尝试使用托管在我的 Web 服务器上的 JSON 文件中的纬度和经度值创建一个多边形数组。我目前有一个用于标记 JSON 数组的实现,它使用 40 多个标记填充地图。

但是,我在创建多边形以使用它们的坐标在我的地图视图上勾勒出一些建筑物时遇到了困难。

一些错误包括:无法解析方法'.position(com.google.android.gms.maps.model.LatLng)'

我知道我必须实现一种方法来设置多边形的颜色、宽度等,但这超出了我的知识范围,我希望有人能帮助我。

我在 MainActivity 中包含错误代码,这是我在应用程序中使用的唯一 Activity。我还将在我的手机中包含应用程序的当前视图,以及我想将多边形数组作为图像做什么。

如果需要,我会提供更多详细信息。

JSON 标记数组:http://i.imgur.com/WN7IR5h.png(我的应用的当前状态)

JSON 多边形数组:http://bl.ocks.org/anonymous/raw/273e0a8dee67740f6431/(未来状态)

代码错误

 // Start polygon from JSON
protected void retrieveAndAddPolygon() throws IOException {
    HttpURLConnection conn = null;
    final StringBuilder json = new StringBuilder();
    try {
        // Connect to the web service
        URL url = new URL(POLYGON_URL);
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Read the JSON data into the StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            json.append(buff, 0, read);
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error connecting to service", e);
        throw new IOException("Error connecting to service", e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    // Create markers for the city data.
    // Must run this on the UI thread since it's a UI operation.
    runOnUiThread(new Runnable() {
        public void run() {
            try {
                createPolygonFromJson(json.toString());
            } catch (JSONException e) {
                Log.e(LOG_TAG, "Error processing JSON", e);
            }
        }
    });
}

void createPolygonFromJson(String json) throws JSONException {
    // De-serialize the JSON string into an array of city objects
    JSONArray jsonArrayPoly = new JSONArray(json);
    for (int i = 0; i < jsonArrayPoly.length(); i++) {
        // Create a marker for each city in the JSON data.
        JSONObject jsonObj = jsonArrayPoly.getJSONObject(i);
        map.addPolygon(new PolygonOptions()
                        //.title(jsonObj.getString("name"))
                        .position(new LatLngPoly(
                                jsonObj.getJSONArray("latlngPoly").getDouble(0),
                                jsonObj.getJSONArray("latlngPoly").getDouble(1)
                        ))
        );
    }
}
// End polygon from JSON

MainActivity.java

package com.example.ramap;

    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.SupportMapFragment;
    import com.google.android.gms.maps.model.BitmapDescriptorFactory;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.Marker;
    import com.google.android.gms.maps.model.MarkerOptions;
    import com.google.android.gms.maps.model.Polygon;
    import com.google.android.gms.maps.model.PolygonOptions;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import android.graphics.Color;
    import android.os.Bundle;
    import android.support.v4.app.FragmentActivity;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    import android.widget.Toast;

    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;

    public class MainActivity extends FragmentActivity {
    private static final String LOG_TAG = "RaMap";

    private static final String SERVICE_URL =                  "http://nrdyninja.com/android/ramap/locations.json";

private static final String POLYGON_URL =    "http://nrdyninja.com/android/ramap/locationsPoly.json";

protected GoogleMap map;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);  // references layout/main.xml to the initial view
    setUpMapIfNeeded();             // sets up the MapView

    // Used for finding current location with button
    // Will eventually pass current location into a value so that markers
    // are populated when they're 5m from current location.
    map.setMyLocationEnabled(true);
    map.getUiSettings().setMyLocationButtonEnabled(true);

    final TextView locationText = (TextView) findViewById(R.id.checkInLocation);
    Button getAnswerButton = (Button) findViewById(R.id.checkInButton);

    getAnswerButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            String answer = "Checked Into <location name here>"; //
            locationText.setText(answer);
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is
    // present.
    getMenuInflater().inflate(R.menu.main, menu); //uses menu/main.xml <item> to populate
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_normal:
            map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            return true;

        case R.id.action_hybrid:
            map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
            return true;

        case R.id.action_satellite:
            map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
protected void onResume() {
    super.onResume();
    setUpMapIfNeeded();
}

private void setUpMapIfNeeded() {
    if (map == null) {
        map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        if (map != null) {
            setUpMap();
        }
    }
}

private void setUpMap() {
    // Retrieve the city data from the web service
    // In a worker thread since it's a network operation.
    new Thread(new Runnable() {
        public void run() {
            try {
                retrieveAndAddCities();
                retrieveAndAddPolygon();
            } catch (IOException e) {
                Log.e(LOG_TAG, "Cannot retrieve cities", e);
                return;
            }
        }
    }).start();
}

protected void retrieveAndAddCities() throws IOException {
    HttpURLConnection conn = null;
    final StringBuilder json = new StringBuilder();
    try {
        // Connect to the web service
        URL url = new URL(SERVICE_URL);
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Read the JSON data into the StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            json.append(buff, 0, read);
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error connecting to service", e);
        throw new IOException("Error connecting to service", e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    // Create markers for the city data.
    // Must run this on the UI thread since it's a UI operation.
    runOnUiThread(new Runnable() {
        public void run() {
            try {
                createMarkersFromJson(json.toString());
            } catch (JSONException e) {
                Log.e(LOG_TAG, "Error processing JSON", e);
            }
        }
    });
}


// Start polygon from JSON
protected void retrieveAndAddPolygon() throws IOException {
    HttpURLConnection conn = null;
    final StringBuilder json = new StringBuilder();
    try {
        // Connect to the web service
        URL url = new URL(POLYGON_URL);
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Read the JSON data into the StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            json.append(buff, 0, read);
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error connecting to service", e);
        throw new IOException("Error connecting to service", e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    // Create markers for the city data.
    // Must run this on the UI thread since it's a UI operation.
    runOnUiThread(new Runnable() {
        public void run() {
            try {
                createPolygonFromJson(json.toString());
            } catch (JSONException e) {
                Log.e(LOG_TAG, "Error processing JSON", e);
            }
        }
    });
}

void createPolygonFromJson(String json) throws JSONException {
    // De-serialize the JSON string into an array of city objects
    JSONArray jsonArrayPoly = new JSONArray(json);
    for (int i = 0; i < jsonArrayPoly.length(); i++) {
        // Create a marker for each city in the JSON data.
        JSONObject jsonObj = jsonArrayPoly.getJSONObject(i);
        map.addPolygon(new PolygonOptions()
                        //.title(jsonObj.getString("name"))
                        .position(new LatLngPoly(
                                jsonObj.getJSONArray("latlngPoly").getDouble(0),
                                jsonObj.getJSONArray("latlngPoly").getDouble(1)
                        ))
        );
    }
}
// End polygon from JSON


void createMarkersFromJson(String json) throws JSONException {
    // De-serialize the JSON string into an array of city objects
    JSONArray jsonArray = new JSONArray(json);
    for (int i = 0; i < jsonArray.length(); i++) {
        // Create a marker for each city in the JSON data.
        JSONObject jsonObj = jsonArray.getJSONObject(i);
        map.addMarker(new MarkerOptions()
                        .title(jsonObj.getString("name"))
                        .snippet(Integer.toString(jsonObj.getInt("check ins")))
                        .position(new LatLng(
                                jsonObj.getJSONArray("latlng").getDouble(0),
                                jsonObj.getJSONArray("latlng").getDouble(1)
                        ))
        );
    }
}
}

【问题讨论】:

    标签: android json google-maps google-maps-android-api-2 polygon


    【解决方案1】:

    据我了解,您正确检索了所有点并且现在想要显示这些点的多边形?

    其实很简单。

    GoogleMap map;
    // ... get a map.
    // Add a triangle in the Gulf of Guinea
    Polygon polygon = map.addPolygon(new PolygonOptions()
     .add(new LatLng(0, 0), new LatLng(0, 5), new LatLng(3, 5), new LatLng(0, 0))
     .strokeColor(Color.RED)
     .fillColor(Color.BLUE));
    

    取自官方文档。 http://developer.android.com/reference/com/google/android/gms/maps/model/Polygon.html

    您的代码应如下所示:

    void createPolygonFromJson(String json) throws JSONException {
    // De-serialize the JSON string into an array of city objects
    PolygonOptions polygonOptions = new PolygonOptions();
    polygonOptions.strokeColor(Color.RED);
    polygonOptions.fillColor(Color.BLUE);
    JSONArray jsonArrayPoly = new JSONArray(json);
    for (int i = 0; i < jsonArrayPoly.length(); i++) {
        // Create a marker for each city in the JSON data.
        JSONObject jsonObj = jsonArrayPoly.getJSONObject(i);
        polygonOptions.add(new LatLng(jsonObj.getJSONArray("latlngPoly").getDouble(0),jsonObj.getJSONArray("latlngPoly").getDouble(1)));
        );
    }
    Polygon polygon = map.addPolygon(polygonOptions);
    

    }

    【讨论】:

    • 我还应该添加:createPolygonFromJson(json.toString());到runOnUiThread?
    • @LordBahamut,是的。你不应该从后台线程中触摸你的 UI。
    • 嗯,好像没用。它不是在地图视图上创建多边形形状。也许我的 JSON 值格式不正确?
    • @LordBahamut,尝试第一个示例,以确保多边形确实在创建(我的第一个 sn-p 代码)。然后尝试检查你的 json 值。
    • 我无法复制正确的结果,但是,我会继续测试直到它起作用。一旦我设法让它工作,我会在几天内接受你的回答。
    猜你喜欢
    • 2014-12-22
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 2012-06-15
    • 1970-01-01
    • 2014-04-02
    相关资源
    最近更新 更多