Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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

like image 324
roa.tah Avatar asked Nov 23 '13 18:11

roa.tah


2 Answers

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
    }
}
like image 90
Steve Benett Avatar answered Oct 12 '22 23:10

Steve Benett


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 :)

like image 37
hassan moradnezhad Avatar answered Oct 13 '22 00:10

hassan moradnezhad