如何从网上JSON标志着谷歌地图上的经纬度 [英] how to mark latitude and longitude on google map from an online json

查看:410
本文介绍了如何从网上JSON标志着谷歌地图上的经纬度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要读JSON(在线),JSON文件看起来是这样的。经度和纬度的纬度名称和经度的国家。

I want to read latitude and longitude from json(online), the json file looks like this.The latitude is name and longitude is country.

[
  {
    "name": "13.0714562",
    "country": "77.55946348",
    "twitter": "Current Location"
  },
  {
    "name": "13.0714562",
    "country": "77.55946348",
    "twitter": "Current Location"
  },
  {
    "name": "13.0714562",
    "country": "77.55946348",
    "twitter": "Current Location"
  },

  ...................

]

我想通过上面的JSON来绘制地图谷歌android系统中的经度和纬度。

I want to plot the latitude and longitude on the google map in android by the above json.

有关JSON的网址是: - HTTP://hmk$c$c.appspot.com / jsonservlet

The url for json is:- http://hmkcode.appspot.com/jsonservlet

我想使用的AsyncTask下载JSON。下面是我的android code。

I am trying to use asynctask to download the json. Below is my android code.

public class Maps extends Activity {
    private ProgressDialog pDialog;
    private static String url = "http://hmkcode.appspot.com/jsonservlet";
    private static final String latitude = "name";
    private static final String longitude = "country";
    private GoogleMap googleMap;
    float lat, lon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.maps);
        new GetMap().execute();
    }

    private class GetMap extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(Maps.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONArray jsonArr = new JSONArray(jsonStr);
                    for (int i = 0; i < jsonArr.length(); i++) {
                        JSONObject c = jsonArr.getJSONObject(i);

                        String name = c.getString(latitude);
                        String time = c.getString(longitude);
                        double LAT = Double.parseDouble(name);
                        double LON = Double.parseDouble(time);
                        final LatLng Marker = new LatLng(LAT, LON);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            try {
                if (googleMap == null) {
                    googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
                    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Marker, 15));
                    @SuppressWarnings("unused")
                    Marker TP = googleMap.addMarker(new MarkerOptions().position(Marker).title("Revamp 15,click on the arrow below for directions"));
                }

                googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

                @SuppressWarnings("unused")
                Marker TP = googleMap.addMarker(new MarkerOptions().position(Marker).title("Revamp 15,click on the arrow below for directions"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

不过,我得到一个错误的 onPostExecute的AsyncTask的部分标记无法解析到一个变量。所以,我试图通过空并初始化标记。如果我这样做的JSON不会被加载到标记变量。

But I get an error in onPostExecute part of asynctask that Marker cannot be resolved to a variable. So I tried to intialize marker by null. If I do that the json does not get loaded in to the Marker variable.

我如何可以加载JSON的标记变量?

How can I load the json in Marker Variable?

推荐答案

它说标记不能被解析为一个变量。
基本上,onPostExecute您发送标记这是不变量。这是一类。

It says "Marker cannot be resolved to a variable". Basically, in onPostExecute you are sending Marker which is not variable. It's a class.

我不知道,如果你甚至可以编译这个code?你得到编译错误还是什么?

I'm not sure if you can even compile this code? You get compilation error or what?

final LatLng Marker = new LatLng(LAT, LON);

而不是标记的尝试将其命名为标记。而做到这一点作为一个全局变量。然后在执行后再次使用它作为标记。

Instead of "Marker" try naming it "marker". And do it as a global variable. Then in post execute use it again as "marker".

永远不要使用类名作为变量名。从命名约定

Don't ever use class names as variable name. From naming convention:

局部变量,实例变量和类变量也写在lowerCamelCase

Local variables, instance variables, and class variables are also written in lowerCamelCase

此外,代替使用全局变量,则可以只将其作为在异步任务的结果。事情是这样的。

Also, instead of using global variable, you could just send it as a result in your async task. Something like this

private class GetMap extends AsyncTask<Void, Void, LatLng>{

    @Override
    protected LatLng doInBackground(Void... voids) {
        // code...
        return new LatLng(LAT, LON);
    }

    @Override
    protected void onPostExecute(LatLng markerLatLng) {
        // code
        Marker TP = googleMap.addMarker(new MarkerOptions().position(markerLatLng).title("Revamp 15,click on the arrow below for directions"));
        // code
    }
}

编辑:像这样的东西也许尝试?这个如果你没有安装谷歌地图准确,和其他一切工作的罚款(你可以检查你的文章的评论)才有效。

Maybe try with something like this? This will only work if you did setup the google maps correctly, and everything else is working fine (you could check the comments on your post).

public class GetMap extends AsyncTask<Void, Void, List<LatLng>> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(Maps.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected List<LatLng> doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                List<LatLng> latLngList = new ArrayList<>();
                JSONArray jsonArr = new JSONArray(jsonStr);
                for (int i = 0; i < jsonArr.length(); i++) {
                    JSONObject c = jsonArr.getJSONObject(i);

                    String name = c.getString(latitude);
                    String time = c.getString(longitude);
                    double LAT = Double.parseDouble(name);
                    double LON = Double.parseDouble(time);
                    latLngList.add(new LatLng(LAT, LON));
                }
                return latLngList;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(List<LatLng> result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        if (result == null){
            // Error occured, handle it as you wish (log, toast, dialog)
            return;
        }else if(result.size() == 0){
            // There was no any result, handle this as you wish (log, toast, dialog)
            return;
        }
        try {
            if (googleMap == null) {
                googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
                //there is no point of moving camera from one marker to another, so we will just move to first one
                googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(result.get(0), 15));
            }
            googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            for(LatLng latLng : result)
                googleMap.addMarker(new MarkerOptions().position(latLng).title("Revamp 15,click on the arrow below for directions"));

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

这篇关于如何从网上JSON标志着谷歌地图上的经纬度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆