简体   繁体   中英

how to get longitude,latitude from the city name android code

I want to convert a text taken from a text field which contains the city name, and I want to convert it to longitude and latitude.

this is what I made:

String location=city.getText().toString();
            String inputLine = "";
            String result = "";
            location=location.replaceAll(" ", "%20");
            String myUrl="http://maps.google.com/maps/geo?q="+location+"&output=csv";
            try{
             URL url=new URL(myUrl);
             URLConnection urlConnection=url.openConnection();
             BufferedReader in = new BufferedReader(new 
             InputStreamReader(urlConnection.getInputStream()));
              while ((inputLine = in.readLine()) != null) {
              result=inputLine;
              }
               lat = result.substring(6, result.lastIndexOf(","));
               longi = result.substring(result.lastIndexOf(",") + 1);
             }
             catch(Exception e){
             e.printStackTrace();
             }

            //////////////////////////////////
            if (location=="" ) 
            {           
             latitude=loc.getLatitude();
            longitude=loc.getLongitude();
            }
            else 
            {
                latitude=Double.parseDouble(lat);
                longitude=Double.parseDouble(longi);
            }

but the code doesn't take the else statement

I changed the URL to this:

String myUrl="http://maps.googleapis.com/maps/api/geocode/json?address="+location+"&sensor=true";

and this is the result:

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Nablus",
               "short_name" : "Nablus",
               "types" : [ "locality", "political" ]
            }
         ],
         "formatted_address" : "Nablus",
         "geometry" : {
            "location" : {
               "lat" : 32.22504,
               "lng" : 35.260971
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 32.2439165,
                  "lng" : 35.2929858
               },
               "southwest" : {
                  "lat" : 32.20615960000001,
                  "lng" : 35.2289562
               }
            }
         },
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}

how could I use latitude and longitude in my code??

There is an easier way by using the Geocoder . It does pretty much the same as the Geocoding API.

if(Geocoder.isPresent()){
    try {
        String location = "theNameOfTheLocation";
        Geocoder gc = new Geocoder(this);
        List<Address> addresses= gc.getFromLocationName(location, 5); // get the found Address Objects

        List<LatLng> ll = new ArrayList<LatLng>(addresses.size()); // A list to save the coordinates if they are available
        for(Address a : addresses){
            if(a.hasLatitude() && a.hasLongitude()){
                ll.add(new LatLng(a.getLatitude(), a.getLongitude()));
            }  
        }  
    } catch (IOException e) {
         // handle the exception
    }
}

it's too late but for others that have same problem
after 4 days i get longitude and latitude from the city name

i used

http://maps.googleapis.com/maps/api/geocode/json?address=tehran&sensor=false

where "tehran" is the city name

by this link you can get a json as below

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Tehran",
               "short_name" : "Tehran",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Tehran",
               "short_name" : "Tehran",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Tehran Province",
               "short_name" : "Tehran Province",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "Iran",
               "short_name" : "IR",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Tehran, Tehran Province, Iran",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 35.8345498,
                  "lng" : 51.6062163
               },
               "southwest" : {
                  "lat" : 35.5590784,
                  "lng" : 51.0934209
               }
            },
            "location" : {
               "lat" : 35.6891975,
               "lng" : 51.3889736
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 35.8345498,
                  "lng" : 51.6062163
               },
               "southwest" : {
                  "lat" : 35.5590784,
                  "lng" : 51.0934209
               }
            }
         },
         "place_id" : "ChIJ2dzzH0kAjj8RvCRwVnxps_A",
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}

so as you can see there are the attribute that we need in "location" object
as this answer said at first we need to get Json from top URL
so easily we add JsonTask Class

private class JsonTask extends AsyncTask<String, String, String> {

    protected void onPreExecute() {
        super.onPreExecute();
        // u can use a dialog here
    }

    protected String doInBackground(String... params) {


        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();


            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = "";

            while ((line = reader.readLine()) != null) {
                buffer.append(line+"\n");
                Log.d("Response: ", "> " + line);   //here u ll get whole response...... :-) 

            }

            return buffer.toString();


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // here "result" is json as stting
    }
}
}

to call and save JSON string you need this code

JsonTask getRequest = new JsonTask();
String JSONString = getRequest.execute("Url address here").get();

then we should get longitude and latitude. so here is s.th that we need

JSONObject jsonResponse1;
try {
    jsonResponse1 = new JSONObject(jsonMap1);
    JSONArray cast = jsonResponse1.getJSONArray("results");
    for (int i = 0; i < cast.length(); i++) {
        JSONObject actor = cast.getJSONObject(i);
        JSONObject name = actor.getJSONObject("geometry");
        JSONObject location = name.getJSONObject("location");
        lat1 = location.getString("lat");
        lng1 = location.getString("lng");
    }
} catch (JSONException e) {
    Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
}

lat1 and lng1 has the values :)

Using the new API you get back a JSON object. Instead of parsing it as a string, parse it as a JSON object. Here is (finally) code that compiles and returns the correct values for the JSON string you gave.

try
{
    org.json.JSONObject jso = new JSONObject(result);
    org.json.JSONArray jsa = jso.getJSONArray("results");
    org.json.JSONObject js2 = jsa.getJSONObject(0);
    org.json.JSONObject js3 = js2.getJSONObject("geometry");
    org.json.JSONObject js4 = js3.getJSONObject("location");
    Double lat = (Double)js4.getDouble("lat");
    Double lng = (Double)js4.getDouble("lng");

}
catch(JSONException jse)
{
    jse.printStackTrace();
}

android.location.Geocoder contains a method getFromLocationName , which returns a list of Addresses. You can query the address for its lat & long.

Geocoder gcd = new Geocoder(context, Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(lat, lng, 1);
if (addresses.size() > 0) 
    System.out.println(addresses.get(0).getLocality());

public static LatLng getCityLatitude(Context context, String city) { Geocoder geocoder = new Geocoder(context,context.getResources().getConfiguration().locale); List<Address> addresses = null; LatLng latLng = null; try { addresses = geocoder.getFromLocationName(city, 1); Address address = addresses.get(0); latLng = new LatLng(address.getLatitude(), address.getLongitude()); } catch (Exception e) { e.printStackTrace(); } return latLng; }

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