简体   繁体   中英

How can I create google maps markers from a JSON file with multiple latitude and longitude coordinates

I have a JSON file with multiple latitudes and longitude coordinates. With this data, I want to create multiple google maps markers.

I tried to parse the JSON file with a for loop and save the long and lat in double variables to map them.

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


   /* // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));*/
}

private void jsonParse() {

    String url = "https://api.myjson.com/bins/kp9wz";
    Log.d(TAG, "jsonParse: is now in jsonParse ");

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "onResponse: is before try");
                    try {
                        JSONArray jsonArray = response.getJSONArray("addresses");

                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject address = jsonArray.getJSONObject(i);

                            String firstName = address.getString("name");
                            Double latitude = Double.parseDouble(address.getString("latitude"));
                            Double longitude = Double.parseDouble(address.getString("longitude"));

                            LatLng sydney = new LatLng(latitude, longitude);
                            mMap.addMarker(new MarkerOptions().position(sydney).title("Test Markers"));
                        }
                        Log.d(TAG, "onResponse: is after for loop");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });
    mQueue.add(request);
}`

You may need to properly zoom the camera for things to render properly. After adding your marker, try something like this:

mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, DEFAULT_ZOOM_LEVEL));

https://api.myjson.com/bins/kp9wz上的文件包含员工,名字,年龄等。它不包含“名称”,“纬度”或“经度”

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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