How to convert an address to a latitude/longitude?

前端 未结 18 2875
难免孤独
难免孤独 2020-11-29 16:21

How would I go about converting an address or city to a latitude/longitude? Are there commercial outfits I can \"rent\" this service from? This would be used in a commercial

18条回答
  •  一生所求
    2020-11-29 16:53

    Try with this code, i work like this with addresses:

    It is link in which with GET method you will send request and get lat and lng. http://maps.google.com/maps/api/geocode/json?address=YOUR ADDRES&sensor=false

    For exemple: http://maps.google.com/maps/api/geocode/json?address=W Main St, Bergenfield, NJ 07621&sensor=false

    1. Create your GET method.

     public static String GET(String url) throws Exception {//GET Method
            String result = null;
            InputStream inputStream = null;
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);
    
            Log.v("ExecuteGET: ", httpGet.getRequestLine().toString());
    
            HttpResponse httpResponse = httpclient.execute(httpGet);
            inputStream = httpResponse.getEntity().getContent();
            if (inputStream != null) {
                result = convertInputStreamToString(inputStream);
                Log.v("Result: ", "result\n" + result);
            } 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    

    2. Create method for send request

    @SuppressWarnings("deprecation")
        public static String getLatLng(String accessToken) throws Exception{
            String query=StaticString.gLobalGoogleUrl+"json?address="+URLEncoder.encode(accessToken)+"&sensor=false";
            Log.v("GETGoogleGeocoder", query+"");
            return GET(query);
        }
    

    gLobalGoogleUrl="http://maps.google.com/maps/api/geocode/"

    3. Call method getLatLng

    String result=getLatLng("W Main St, Bergenfield, NJ 07621");
    

    4. Parse JSONObject

    Now result is JSONObject with information about address and lan,lng. Parse JSONObject (result) with gson(). After that use lat,lng.

    If you have question about code , ask.

提交回复
热议问题