简体   繁体   English

如何在Android的地图活动中从URL获取JSON数据

[英]How to get JSON data from a url in a map activity for android

Hi I wanted to know how I can get JSON data from a URL and put that into a map activity in android studio, which would replace the default location, which is syndey? 嗨,我想知道如何从URL获取JSON数据并将其放入android studio中的地图活动中,该活动将替换默认位置,即syndey? I cannot figure out how to do this as most tutorials online not make sense. 我无法弄清楚该如何做,因为大多数在线教程都没有意义。

This is the data, which I want to retrieve via the URL 这是我要通过URL检索的数据

{"Users":[{"name":"Diaz","lon":"51.1251635","lat":"51.296910"},{"name":"Chris","lon":"51.139409","lat":"51.295825"}}

This is the default code generated by the map activity 这是地图活动生成的默认代码

import android.os.Bundle;
import android.renderscript.ScriptGroup;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    private GoogleMap nMap;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney, Australia, and move the camera.
        LatLng sydney = new LatLng(512.33,11.2333);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydeny));
        mMap.getMaxZoomLevel();
    }


}

Firstly, to display your current location on the map. 首先,在地图上显示您的当前位置。 All you need to do is get the co-ordinate of your preferred location using google map. 您需要做的就是使用Google Map获取首选位置的坐标。 You can now create a LatLng object using this value. 现在,您可以使用此值创建LatLng对象。 Your app currently displays sidney because that is where the Map camera is position. 您的应用当前显示sidney,因为这是Map摄像头所在的位置。 You also have a marker at that same LatLng. 您在同一LatLng也有一个标记。

You can simple get the coordinates of where ever location you want to display and pass it into the Map object. 您可以简单地获取要显示的位置的坐标,并将其传递到Map对象中。

Back to your main question which is getting a JSON data from a URL; 回到您的主要问题,这是从URL获取JSON数据; i can say that it is pretty easy to achieve and based on the context from which you are asking, i can infer that you are maybe trying to query the google map api. 我可以说这很容易实现,并且根据您所询问的上下文,我可以推断出您可能正在尝试查询google map api。

A library like Retrofit( http://square.github.io/retrofit/ ) would help you get this done easily. 诸如Retrofit( http://square.github.io/retrofit/ )之类的库将帮助您轻松完成此任务。 Just do not forget to execute the operation from a background thread. 只是不要忘记从后台线程执行操作。

Using basic HttpURLConnection 使用基本的HttpURLConnection

public JSONObject queryGoogleDistanceApi(String origin, String destination, String API_KEY_PLACES) throws Exception{
    String Url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + origin + "&destinations=" + destination + "&mode=driving&language=en&key=" + API_KEY_PLACES;

    HttpURLConnection conn = null;
    StringBuilder jsonResults = new StringBuilder();
    URL url = new URL(Url);
    Log.d(TAG, Url);
    conn = (HttpURLConnection) url.openConnection();
    InputStreamReader in = new InputStreamReader(conn.getInputStream());
    // Load the results into a StringBuilder
    int read;
    char[] buff = new char[1024];
    while ((read = in.read(buff)) != -1) {
        jsonResults.append(buff, 0, read);
    }
    if (conn != null) {
        conn.disconnect();
    }

    JSONObject object = new JSONObject(jsonResults.toString());
    return object;
}

you must call your api in onMapReady method. 您必须在onMapReady方法中调用您的api。 then parse it and set markers from your data. 然后解析它并根据您的数据设置标记。 like below code: 像下面的代码:

 @Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    //call your api. get son data
    //{"Users":[{"name":"Diaz","lon":"51.1251635","lat":"51.296910"},{"name":"Chris","lon":"51.139409","lat":"51.295825"}}

    // Add a marker from JSON data, and move the camera.
    LatLng diaz = new LatLng(51.296910,51.1251635);
    mMap.addMarker(new MarkerOptions().position(diaz).title("Diaz"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(diaz));
    mMap.getMaxZoomLevel();
}

I think that you can parse Json data. 我认为您可以解析Json数据。 if you have problem in parse Json data, I can help you again. 如果您在解析Json数据时遇到问题,我可以再次为您提供帮助。

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

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