简体   繁体   English

在Android中解析Google Maps Marker的JSON响应

[英]Parse JSON response for Google Maps Marker in Android

I am trying to retrieve a JSON response from the server, parse it and add markers to my map. 我正在尝试从服务器检索JSON响应,对其进行解析并将标记添加到我的地图中。 I have a working map, and have added buttons to it, one of which I'd like to load markers from the server. 我有一个工作地图,并向其中添加了按钮,我想从服务器中加载标记之一。 Calling an action like this: 调用这样的动作:

 public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnLoc:
                if(LocOn == 0){
                    googleMap.setMyLocationEnabled(true);
                    double lat= googleMap.getMyLocation().getLatitude();
                    double lng = googleMap.getMyLocation().getLongitude();
                    LatLng ll = new LatLng(lat, lng);
                    googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(ll, 18));
                    Loc.setBackgroundResource(R.drawable.loc);
                    LocOn = 1;
                    LoadMarkers.setText("Clear Markers");
                    GetMarkers markers = new GetMarkers();
                    markers.execute();


                } else {
                    LocOn = 0;
                    Loc.setBackgroundResource(R.drawable.noloc);
                    LoadMarkers.setText("Load Markers");
                    googleMap.clear();
                }

        }
    }

The "GetMarkers" action will call this: “ GetMarkers”操作将调用此命令:

class GetMarkers extends AsyncTask<User, Void, List<JMarker>>{

@Override
protected List<JMarker> doInBackground(User... params) {

    try {
        URL url = new URL("someurl.php");
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        String param = "username="+user.username+"&pw="+user.password;
        OutputStream out = conn.getOutputStream();
        DataOutputStream dataOut = new DataOutputStream(out);
        dataOut.writeBytes(param.trim());

        InputStream in = conn.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        StringBuilder builder = new StringBuilder();
        while((line = reader.readLine()) != null) {
            builder.append(line);
        }
        reader.close();
        String response = builder.toString();

        System.out.println(response); //This works, I'm getting a JSON response. Just need to parse it and return it to onPostExecute for processing. 

    }

    catch (IOException e) {
        e.printStackTrace();
    }

    return null; //This will eventually return the JSON object
}
@Override
protected void onPostExecute(List<JMarker> jMarkers) {
    for(JMarker marker: jMarkers) {
        LatLng position = new LatLng(marker.LAT, marker.LNG);
        googleMap.addMarker(new MarkerOptions().position(position));
    }
}

} }

The onPostExecute, am trying to add the eventually returned markers to the map. onPostExecute正在尝试将最终返回的标记添加到地图中。

I am hoping someone can help me out. 我希望有人可以帮助我。 Thank you in advance. 先感谢您。

u have NPE in Map.java at line 148 i suppose 我想在Map.java的第148行有NPE

I suppose this is 我想这是

BufferedReader reader = new BufferedReader(new InputStreamReader(in));

meaning your input stream is null. 表示您的输入流为空。

two things here: 这里有两件事:

1) you should close your OutputStream before get response (out.close()) 1)您应该在获得响应之前关闭OutputStream(out.close())

2) when getting response if code>200 you will not get anything from conn.getInputStream(); 2)如果代码> 200时获得响应,则不会从conn.getInputStream()得到任何信息; but from conn.getErrorStream() mening there is server error. 但是从conn.getErrorStream()来看,存在服务器错误。

you can apply smth like that: 您可以这样应用:

 StringBuffer response = new StringBuffer();
    System.out.println(conn.getResponseCode());
    try {
        BufferedReader in;

        if (conn.getResponseCode() > 299) {
            in = new BufferedReader(
                    new InputStreamReader(conn.getErrorStream()));
        } else {
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
        }
        String inputLine;


        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

However I would drop the AsyncTask I would use http client as Retrofit or Volley as it handles gracefully lots of http scenarios. 但是,我会放弃AsyncTask,因为它将优雅地处理许多HTTP场景,所以我将使用HTTP客户端作为Retrofit或Volley。

The answers and comments I received helped me "scratch my head" and arrive at this answer. 我收到的答案和评论帮助我“抓头”并得出了答案。 The reason the app was not working, and crashing, is because I was passing null values, to the parameters. 应用程序无法运行并崩溃的原因是因为我将空值传递给了参数。 Once I passed the information along, I was able to get the JSON response, create a JSONArray and return that. 传递完信息后,便可以获取JSON响应,创建一个JSONArray并将其返回。 Once it was sent to the onPostExecute, I parsed the JSONArray there, and added the markers. 一旦将其发送到onPostExecute,我在那里解析了JSONArray,并添加了标记。 Working code: 工作代码:

First, I initiate the task. 首先,我启动任务。

GetMarkers markers = new GetMarkers();
markers.execute(user); //pass the user to the task

Task: 任务:

class GetMarkers extends AsyncTask<User, Void, JSONArray>{

        User markeruser = new User(userLocalStore.getLoggedInUser().username, userLocalStore.getLoggedInUser().password);
        JSONArray jsonarray = null;
        @Override
        protected JSONArray doInBackground(User... params) {

            try {
                URL url = new URL("https://someurl.com/file.php");
                HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                String param = "Username="+markeruser.username+"&pw="+markeruser.password;
                OutputStream out = conn.getOutputStream();
                DataOutputStream dataOut = new DataOutputStream(out);
                dataOut.writeBytes(param.trim());

                InputStream in = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String line;
                StringBuilder builder = new StringBuilder();
                while((line = reader.readLine()) != null) {
                    builder.append(line);
                }
                reader.close();
                String response = builder.toString();

                jsonarray = new JSONArray(response);
            }

            catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return jsonarray;
        }

        @Override
        protected void onPostExecute(JSONArray jsonarray) {

            try {

                for(int i=0; i<jsonarray.length(); i++){
                    JSONObject obj = jsonarray.getJSONObject(i);

                    String PT = obj.getString("NUMBER");
                    Double LAT = obj.getDouble("LATITUDE");
                    Double LNG = obj.getDouble("LONGITUDE");
                    LatLng position = new LatLng(LAT, LNG);

                    String title = "PT: " + PT;

                    googleMap.addMarker(new MarkerOptions().position(position).title(title).icon(BitmapDescriptorFactory.fromResource(R.drawable.red)));
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM