Как разобрать URL?

Вот какой рабочий код, который использует API веб-сервисов Places, это поможет вам получить нужную функциональность.

Здесь можно найти общую документацию здесь .

Здесь можно найти доступные типы мест типа .

Ниже приведен простой пример. Сначала создайте строку запроса для API:

public StringBuilder sbMethod() {

    //use your current location here
    double mLatitude = 37.77657;
    double mLongitude = -122.417506;

    StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
    sb.append("location=" + mLatitude + "," + mLongitude);
    sb.append("&radius=5000");
    sb.append("&types=" + "restaurant");
    sb.append("&sensor=true");
    sb.append("&key=******* YOUR API KEY****************");

    Log.d("Map", "api: " + sb.toString());

    return sb;
}

Здесь AsyncTask используется для запроса API-интерфейсов:

private class PlacesTask extends AsyncTask {

    String data = null;

    // Invoked by execute() method of this object
    @Override
    protected String doInBackground(String... url) {
        try {
            data = downloadUrl(url[0]);
        } catch (Exception e) {
            Log.d("Background Task", e.toString());
        }
        return data;
    }

    // Executed after the complete execution of doInBackground() method
    @Override
    protected void onPostExecute(String result) {
        ParserTask parserTask = new ParserTask();

        // Start parsing the Google places in JSON format
        // Invokes the "doInBackground()" method of the class ParserTask
        parserTask.execute(result);
    }
}

Вот метод downloadURL() :

private String downloadUrl(String strUrl) throws IOException {
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(strUrl);

        // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

        StringBuffer sb = new StringBuffer();

        String line = "";
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        data = sb.toString();

        br.close();

    } catch (Exception e) {
        Log.d("Exception while downloading url", e.toString());
    } finally {
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}

ParserTask для разбора результата JSON:

private class ParserTask extends AsyncTask>> {

    JSONObject jObject;

    // Invoked by execute() method of this object
    @Override
    protected List> doInBackground(String... jsonData) {

        List> places = null;
        Place_JSON placeJson = new Place_JSON();

        try {
            jObject = new JSONObject(jsonData[0]);

            places = placeJson.parse(jObject);

        } catch (Exception e) {
            Log.d("Exception", e.toString());
        }
        return places;
    }

    // Executed after the complete execution of doInBackground() method
    @Override
    protected void onPostExecute(List> list) {

        Log.d("Map", "list size: " + list.size());
        // Clears all the existing markers;
        mGoogleMap.clear();

        for (int i = 0; i < list.size(); i++) {

            // Creating a marker
            MarkerOptions markerOptions = new MarkerOptions();

            // Getting a place from the places list
            HashMap hmPlace = list.get(i);


            // Getting latitude of the place
            double lat = Double.parseDouble(hmPlace.get("lat"));

            // Getting longitude of the place
            double lng = Double.parseDouble(hmPlace.get("lng"));

            // Getting name
            String name = hmPlace.get("place_name");

            Log.d("Map", "place: " + name);

            // Getting vicinity
            String vicinity = hmPlace.get("vicinity");

            LatLng latLng = new LatLng(lat, lng);

            // Setting the position for the marker
            markerOptions.position(latLng);

            markerOptions.title(name + " : " + vicinity);

            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));

            // Placing a marker on the touched position
            Marker m = mGoogleMap.addMarker(markerOptions);

        }
    }
}

Place_JSON класс, который используется в ParserTask:

public class Place_JSON {

    /**
     * Receives a JSONObject and returns a list
     */
    public List> parse(JSONObject jObject) {

        JSONArray jPlaces = null;
        try {
            /** Retrieves all the elements in the 'places' array */
            jPlaces = jObject.getJSONArray("results");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        /** Invoking getPlaces with the array of json object
         * where each json object represent a place
         */
        return getPlaces(jPlaces);
    }

    private List> getPlaces(JSONArray jPlaces) {
        int placesCount = jPlaces.length();
        List> placesList = new ArrayList>();
        HashMap place = null;

        /** Taking each place, parses and adds to list object */
        for (int i = 0; i < placesCount; i++) {
            try {
                /** Call getPlace with place JSON object to parse the place */
                place = getPlace((JSONObject) jPlaces.get(i));
                placesList.add(place);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return placesList;
    }

    /**
     * Parsing the Place JSON object
     */
    private HashMap getPlace(JSONObject jPlace) {

        HashMap place = new HashMap();
        String placeName = "-NA-";
        String vicinity = "-NA-";
        String latitude = "";
        String longitude = "";
        String reference = "";

        try {
            // Extracting Place name, if available
            if (!jPlace.isNull("name")) {
                placeName = jPlace.getString("name");
            }

            // Extracting Place Vicinity, if available
            if (!jPlace.isNull("vicinity")) {
                vicinity = jPlace.getString("vicinity");
            }

            latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
            longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
            reference = jPlace.getString("reference");

            place.put("place_name", placeName);
            place.put("vicinity", vicinity);
            place.put("lat", latitude);
            place.put("lng", longitude);
            place.put("reference", reference);

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

Наконец, вызовите этот процесс следующим образом:

    StringBuilder sbValue = new StringBuilder(sbMethod());
    PlacesTask placesTask = new PlacesTask();
    placesTask.execute(sbValue.toString());

Результат:

enter image description here [/g2]

20
задан Felix Kling 29 May 2011 в 14:37
поделиться

1 ответ

Браузеры проделали длинный путь, так как этот вопрос сначала задали. Можно теперь использовать собственный компонент интерфейс URL для выполнения этого:

const url = new URL('http://www.somesite.se/blah/sdgsdgsdgs')

console.log(url.host) // "www.somesite.se"
console.log(url.href) // "http://www.somesite.se/blah/sdgsdgsdgs"
console.log(url.origin) // "http://www.somesite.se"
console.log(url.pathname) // "/blah/sdgsdgsdgs"
console.log(url.protocol) // "http:"
// etc.

знать, что IE не поддерживает этот API. Но, можно легко полизаполнить его polyfill.io:

<script crossorigin="anonymous" src="https://polyfill.io/v3/polyfill.min.js?flags=gated&features=URL"></script>
0
ответ дан 29 November 2019 в 22:26
поделиться
Другие вопросы по тегам:

Похожие вопросы: