我想转换从包含城市名称的文字字段中获取的文字,我想将其转换为经度和纬度。
这就是我所做的:
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);
}
但代码不接受else语句
我将网址更改为:
String myUrl =“http://maps.googleapis.com/maps/api/geocode/json?address=”+ location +“& sensor = true”;
这就是结果:
{
"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"
}
我如何在代码中使用纬度和经度?
答案 0 :(得分:20)
使用Geocoder有一种更简单的方法。它与地理编码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
}
}
答案 1 :(得分:3)
现在为时已晚,但对于其他有同样问题的人来说 4天后,我从城市名称获得经度和纬度
我用过
http://maps.googleapis.com/maps/api/geocode/json?address=tehran&sensor=false
&#34;德黑兰&#34; 是城市名称
通过此链接,您可以获得如下的json
{
"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"
}
所以你可以看到我们需要的属性是&#34; location&#34;对象
正如this answer所说,我们首先需要从顶级网址获取Json
我们很容易添加 JsonTask 类
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
}
}
}
调用并保存您需要此代码的JSON字符串
JsonTask getRequest = new JsonTask();
String JSONString = getRequest.execute("Url address here").get();
那么我们应该得到经度和纬度。所以我们需要
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和lng1的值为:)
答案 2 :(得分:2)
使用新API,您将获得一个JSON对象。而不是将其解析为字符串,将其解析为JSON对象。这是(最终)代码,它编译并返回您给出的JSON字符串的正确值。
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();
}
答案 3 :(得分:0)
android.location.Geocoder
包含方法getFromLocationName
,该方法返回地址列表。您可以查询其lat&amp;的地址。长。
答案 4 :(得分:0)
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());
答案 5 :(得分:0)
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;
}