user6020197
user6020197

Reputation: 121

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? 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

{"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();
    }


}

Upvotes: 0

Views: 5084

Answers (2)

Haniyeh Khaksar
Haniyeh Khaksar

Reputation: 804

you must call your api in onMapReady method. 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. if you have problem in parse Json data, I can help you again.

Upvotes: 0

ribads
ribads

Reputation: 393

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. You can now create a LatLng object using this value. Your app currently displays sidney because that is where the Map camera is position. You also have a marker at that same LatLng.

You can simple get the coordinates of where ever location you want to display and pass it into the Map object.

Back to your main question which is getting a JSON data from a URL; 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.

A library like Retrofit(http://square.github.io/retrofit/) would help you get this done easily. Just do not forget to execute the operation from a background thread.

Using basic 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;
}

Upvotes: 1

Related Questions