How might I obtain the city name in Google Maps if I have latitude and longitude coordinates of a town or area?
如果我有一个城镇或地区的纬度和经度坐标,如何在谷歌地图中获得城市名称?
I tried using the latitude, longitude and I got country but I don't know how to get city name.
我试着用纬度,经度和我的国家,但我不知道如何得到城市名。
14 个解决方案
#1
211
From a Geocoder
object, you can call the getFromLocation(double, double, int)
method. It will return a list of Address
objects that have a method getLocality()
.
从Geocoder对象中,可以调用getFromLocation(double, double, int)方法。它将返回具有getLocality()方法的地址对象列表。
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());
}
else {
// do your stuff
}
#2
23
I am using this code. You can also your this for getting city and other details about a Latitude and longitude :
我正在使用这个代码。你也可以用这个来获取城市和其他关于纬度和经度的细节:
public class getReverseGeoCoding {
private String Address1 = "", Address2 = "", City = "", State = "", Country = "", County = "", PIN = "";
public void getAddress() {
Address1 = "";
Address2 = "";
City = "";
State = "";
Country = "";
County = "";
PIN = "";
try {
JSONObject jsonObj = parser_Json.getJSONfromURL("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + Global.curLatitude + ","
+ Global.curLongitude + "&sensor=true");
String Status = jsonObj.getString("status");
if (Status.equalsIgnoreCase("OK")) {
JSONArray Results = jsonObj.getJSONArray("results");
JSONObject zero = Results.getJSONObject(0);
JSONArray address_components = zero.getJSONArray("address_components");
for (int i = 0; i < address_components.length(); i++) {
JSONObject zero2 = address_components.getJSONObject(i);
String long_name = zero2.getString("long_name");
JSONArray mtypes = zero2.getJSONArray("types");
String Type = mtypes.getString(0);
if (TextUtils.isEmpty(long_name) == false || !long_name.equals(null) || long_name.length() > 0 || long_name != "") {
if (Type.equalsIgnoreCase("street_number")) {
Address1 = long_name + " ";
} else if (Type.equalsIgnoreCase("route")) {
Address1 = Address1 + long_name;
} else if (Type.equalsIgnoreCase("sublocality")) {
Address2 = long_name;
} else if (Type.equalsIgnoreCase("locality")) {
// Address2 = Address2 + long_name + ", ";
City = long_name;
} else if (Type.equalsIgnoreCase("administrative_area_level_2")) {
County = long_name;
} else if (Type.equalsIgnoreCase("administrative_area_level_1")) {
State = long_name;
} else if (Type.equalsIgnoreCase("country")) {
Country = long_name;
} else if (Type.equalsIgnoreCase("postal_code")) {
PIN = long_name;
}
}
// JSONArray mtypes = zero2.getJSONArray("types");
// String Type = mtypes.getString(0);
// Log.e(Type,long_name);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String getAddress1() {
return Address1;
}
public String getAddress2() {
return Address2;
}
public String getCity() {
return City;
}
public String getState() {
return State;
}
public String getCountry() {
return Country;
}
public String getCounty() {
return County;
}
public String getPIN() {
return PIN;
}
}
JSON PARSER CLASS
JSON解析器类
public class parser_Json {
public static JSONObject getJSONfromURL(String url) {
// initialize
InputStream is = null;
String result = "";
JSONObject jObject = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObject = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jObject;
}
}
You can get more info from this question : Get the particular address using latitude and longitude
您可以从这个问题中获得更多信息:使用纬度和经度获取特定的地址
#3
11
Try this
试试这个
List<Address> list = geoCoder.getFromLocation(location
.getLatitude(), location.getLongitude(), 1);
if (list != null & list.size() > 0) {
Address address = list.get(0);
result = address.getLocality();
return result;
#4
7
try below code hope use full for you:-
尝试下面的代码希望您使用充分:-
CityAsyncTask cst = new CityAsyncTask(HomeScreenUserLocation.this,
latitude, longitude);
cst.execute();
String lo = null;
try {
lo = cst.get().toString();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and AsyncTask
和AsyncTask
public class CityAsyncTask extends AsyncTask<String, String, String> {
Activity act;
double latitude;
double longitude;
public CityAsyncTask(Activity act, double latitude, double longitude) {
// TODO Auto-generated constructor stub
this.act = act;
this.latitude = latitude;
this.longitude = longitude;
}
@Override
protected String doInBackground(String... params) {
String result = "";
Geocoder geocoder = new Geocoder(act, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(latitude,
longitude, 1);
Log.e("Addresses", "-->" + addresses);
result = addresses.get(0).toString();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
#5
2
Please refer below code
请参考下面代码
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
String cityName = addresses.get(0).getAddressLine(0);
String stateName = addresses.get(0).getAddressLine(1);
String countryName = addresses.get(0).getAddressLine(2);
#6
2
Try this
试试这个
var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);
geocoder.geocode(
{'latLng': latlng},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add= results[0].formatted_address ;
var value=add.split(",");
count=value.length;
country=value[count-1];
state=value[count-2];
city=value[count-3];
alert("city name is: " + city);
}
else {
alert("address not found");
}
}
else {
alert("Geocoder failed due to: " + status);
}
}
);
);
#7
2
Just Use this method and pass your lat, long.
就用这个方法,把你的腰传过去。
public static void getAddress(Context context, double LATITUDE, double LONGITUDE) {
//Set Address
try {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL
Log.d(TAG, "getAddress: address" + address);
Log.d(TAG, "getAddress: city" + city);
Log.d(TAG, "getAddress: state" + state);
Log.d(TAG, "getAddress: postalCode" + postalCode);
Log.d(TAG, "getAddress: knownName" + knownName);
}
} catch (IOException e) {
e.printStackTrace();
}
return;
}
#8
0
private class MatchingNearByLocationTask extends
AsyncTask<Void, Void, Void>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
progressDialog = new ProgressDialog(mContext);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(true);
progressDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
jsonStr = getLocationInfo(Latitude, Longitude).toString();
if (jsonStr != null) {
Log.i("location--??", jsonStr);
JSONObject jsonObj;
try {
jsonObj = new JSONObject(jsonStr);
String Status = jsonObj.getString("status");
if (Status.equalsIgnoreCase("OK")) {
JSONArray Results = jsonObj.getJSONArray("results");
JSONObject zero = Results.getJSONObject(0);
JSONArray address_components = zero
.getJSONArray("address_components");
for (int i = 0; i < address_components.length(); i++) {
JSONObject zero2 = address_components
.getJSONObject(i);
String long_name = zero2.getString("long_name");
JSONArray mtypes = zero2.getJSONArray("types");
String Type = mtypes.getString(0);
if (Type.equalsIgnoreCase("administrative_area_level_2")) {
// Address2 = Address2 + long_name + ", ";
String City = long_name;
Log.d(" CityName --->", City + "");
}
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
@Override
protected void onCancelled() {
super.onCancelled();
progressDialog.dismiss();
}
}
private JSONObject getLocationInfo(double lat, double lng) {
HttpGet httpGet = new HttpGet(
"http://maps.googleapis.com/maps/api/geocode/json?latlng="
+ lat + "," + lng + "&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
#9
0
You can use this if you have a list:
如果你有一个列表,你可以使用它:
Address address = list.get(0);
String cityname = address.getLocality();
#10
0
com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(data);
if("OK".equals(jsonObject.getString("status"))){
String formatted_address;
JSONArray results = jsonObject.getJSONArray("results");
if(results != null && results.size() > 0){
com.alibaba.fastjson.JSONObject object = results.getJSONObject(0);
String addressComponents = object.getString("address_components");
formatted_address = object.getString("formatted_address");
Log.e("amaya","formatted_address="+formatted_address+"--url="+url);
if(findCity){
boolean finded = false;
JSONArray ac = JSONArray.parseArray(addressComponents);
if(ac != null && ac.size() > 0){
for(int i=0;i<ac.size();i++){
com.alibaba.fastjson.JSONObject jo = ac.getJSONObject(i);
JSONArray types = jo.getJSONArray("types");
if(types != null && types.size() > 0){
for(int j=0;j<ac.size();j++){
String string = types.getString(i);
if("administrative_area_level_1".equals(string)){
finded = true;
break;
}
}
}
if(finded) break;
}
}
Log.e("amaya","city="+formatted_address);
}else{
Log.e("amaya","poiName="+hotspotPoi.getPoi_name()+"--"+hotspotPoi);
}
if(hotspotPoi != null) hotspotPoi.setPoi_name(formatted_address);
EventBus.getDefault().post(new AmayaEvent.GeoEvent(hotspotPoi));
}
}
this is a method to parse google feedback data.
这是一种解析谷歌反馈数据的方法。
#11
0
I got new way to resolve this issue. Here I have used google http service to get total information of location based on longitude and latitude. You just need to pass latitude and longitude in url and your api key (ex : latlng=21.1497409, 79.08747970000002 & key=YOUR API KEY). Here is my get service in ExampleService
Class
我找到了解决这个问题的新方法。这里我使用了谷歌http服务来获取基于经度和纬度的位置信息。您只需在url和api密匙中传递纬度和经度(例如:latlng=21.1497409, 79.08747970000002 & key=您的api密匙)。这是我在考试中得到的服务
getService(url) {
return this.http.get(url).map((data: any) => data.json())
}
this you can put anywhere you want and just call below service from component where you need location data
你可以把它放到你想要的任何地方,然后从需要位置数据的组件调用下面的服务。
this._exampleService.getService("https://maps.googleapis.com/maps/api/geocode/json?latlng=21.1497409, 79.08747970000002&key=YOUR API KEY").subscribe(getplaceData => {
var placeDataDest: any;
placeDataDest = getplaceData;
console.log("i got place id yeee " + placeDataDest['results'][0]['place_id']);
console.log("i got place details yeee " + placeDataDest['results']);
});
similarly find city name....hope you will find this useful
同样....找到城市的名字希望您能发现这一点
#12
0
try using this api :
尝试使用这个api:
URL ": http://maps.googleapis.com/maps/api/geocode/json?latlng="+String.valueOf(yout_lattitude)+","+String.valueOf(your_longitude)
URL:http://maps.googleapis.com/maps/api/geocode/json?latlng= " + String.valueOf(yout_lattitude)+”、“+ String.valueOf(your_longitude)
#13
0
Working code:
工作代码:
addresses = geocoder.getFromLocation(mMap.getCameraPosition().target.latitude, mMap.getCameraPosition().target.longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
String locality = addresses.get(0).getLocality(); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String subLocality = addresses.get(0).getSubLocality(); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
//String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String address1 = addresses.get(0).getAddressLine(1); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String address2 = addresses.get(0).getAddressLine(2); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
// String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
#14
0
import org.json.JSONObject
fun parseLocation(response: String): GeoLocation? {
val geoCodes by lazy { doubleArrayOf(0.0, 0.0) }
val jObj = JSONObject(response)
if (jObj.has(KEY_RESULTS)) {
val jArrResults = jObj.getJSONArray(KEY_RESULTS)
for (i in 0 until jArrResults.length()) {
val jObjResult = jArrResults.getJSONObject(i)
//getting latitude and longitude
if (jObjResult.has(KEY_GEOMETRY)) {
val jObjGeometry = jObjResult.getJSONObject(KEY_GEOMETRY)
if (jObjGeometry.has(KEY_LOCATION)) {
val jObjLocation = jObjGeometry.getJSONObject(KEY_LOCATION)
if (jObjLocation.has(KEY_LAT)) {
geoCodes[0] = jObjLocation.getDouble(KEY_LAT)
}
if (jObjLocation.has(KEY_LNG)) {
geoCodes[1] = jObjLocation.getDouble(KEY_LNG)
}
}
}
var administrativeAreaLevel1: String? = null
//getting city
if (jObjResult.has(KEY_ADDRESS_COMPONENTS)) {
val jArrAddressComponents = jObjResult.getJSONArray(KEY_ADDRESS_COMPONENTS)
for (i in 0 until jArrAddressComponents.length()) {
val jObjAddressComponents = jArrAddressComponents.getJSONObject(i)
if (jObjAddressComponents.has(KEY_TYPES)) {
val jArrTypes = jObjAddressComponents.getJSONArray(KEY_TYPES)
for (j in 0 until jArrTypes.length()) {
when (jArrTypes.getString(j)) {
VALUE_LOCALITY, VALUE_POSTAL_TOWN -> {
return GeoLocation(jObjAddressComponents.getString(KEY_LONG_NAME), *geoCodes)
}
ADMINISTRATIVE_AREA_LEVEL_1 -> {
administrativeAreaLevel1 = jObjAddressComponents.getString(KEY_LONG_NAME)
}
else -> {
}
}
}
}
}
for (i in 0 until jArrAddressComponents.length()) {
val jObjAddressComponents = jArrAddressComponents.getJSONObject(i)
if (jObjAddressComponents.has(KEY_TYPES)) {
val jArrTypes = jObjAddressComponents.getJSONArray(KEY_TYPES)
val typeList = ArrayList<String>()
for (j in 0 until jArrTypes.length()) {
typeList.add(jArrTypes.getString(j))
}
if (typeList.contains(VALUE_SUBLOCALITY)) {
var hasSubLocalityLevel = false
typeList.forEach { type ->
if (type.contains(VALUE_SUBLOCALITY_LEVEL)) {
hasSubLocalityLevel = true
if (type == VALUE_SUBLOCALITY_LEVEL_1) {
return GeoLocation(jObjAddressComponents.getString(KEY_LONG_NAME), *geoCodes)
}
}
}
if (!hasSubLocalityLevel) {
return GeoLocation(jObjAddressComponents.getString(KEY_LONG_NAME), *geoCodes)
}
}
}
}
}
if (geoCodes.isNotEmpty()) return GeoLocation(administrativeAreaLevel1, geoCodes = *geoCodes)
}
}
return null
}
data class GeoLocation(val latitude: Double = 0.0, val longitude: Double = 0.0, val city: String? = null) : Parcelable {
constructor(city: String? = null, vararg geoCodes: Double) : this(geoCodes[0], geoCodes[1], city)
constructor(source: Parcel) : this(source.readDouble(), source.readDouble(), source.readString())
companion object {
@JvmField
val CREATOR = object : Parcelable.Creator<GeoLocation> {
override fun createFromParcel(source: Parcel) = GeoLocation(source)
override fun newArray(size: Int): Array<GeoLocation?> = arrayOfNulls(size)
}
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeDouble(latitude)
dest.writeDouble(longitude)
dest.writeString(city)
}
override fun describeContents() = 0
}
#1
211
From a Geocoder
object, you can call the getFromLocation(double, double, int)
method. It will return a list of Address
objects that have a method getLocality()
.
从Geocoder对象中,可以调用getFromLocation(double, double, int)方法。它将返回具有getLocality()方法的地址对象列表。
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());
}
else {
// do your stuff
}
#2
23
I am using this code. You can also your this for getting city and other details about a Latitude and longitude :
我正在使用这个代码。你也可以用这个来获取城市和其他关于纬度和经度的细节:
public class getReverseGeoCoding {
private String Address1 = "", Address2 = "", City = "", State = "", Country = "", County = "", PIN = "";
public void getAddress() {
Address1 = "";
Address2 = "";
City = "";
State = "";
Country = "";
County = "";
PIN = "";
try {
JSONObject jsonObj = parser_Json.getJSONfromURL("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + Global.curLatitude + ","
+ Global.curLongitude + "&sensor=true");
String Status = jsonObj.getString("status");
if (Status.equalsIgnoreCase("OK")) {
JSONArray Results = jsonObj.getJSONArray("results");
JSONObject zero = Results.getJSONObject(0);
JSONArray address_components = zero.getJSONArray("address_components");
for (int i = 0; i < address_components.length(); i++) {
JSONObject zero2 = address_components.getJSONObject(i);
String long_name = zero2.getString("long_name");
JSONArray mtypes = zero2.getJSONArray("types");
String Type = mtypes.getString(0);
if (TextUtils.isEmpty(long_name) == false || !long_name.equals(null) || long_name.length() > 0 || long_name != "") {
if (Type.equalsIgnoreCase("street_number")) {
Address1 = long_name + " ";
} else if (Type.equalsIgnoreCase("route")) {
Address1 = Address1 + long_name;
} else if (Type.equalsIgnoreCase("sublocality")) {
Address2 = long_name;
} else if (Type.equalsIgnoreCase("locality")) {
// Address2 = Address2 + long_name + ", ";
City = long_name;
} else if (Type.equalsIgnoreCase("administrative_area_level_2")) {
County = long_name;
} else if (Type.equalsIgnoreCase("administrative_area_level_1")) {
State = long_name;
} else if (Type.equalsIgnoreCase("country")) {
Country = long_name;
} else if (Type.equalsIgnoreCase("postal_code")) {
PIN = long_name;
}
}
// JSONArray mtypes = zero2.getJSONArray("types");
// String Type = mtypes.getString(0);
// Log.e(Type,long_name);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String getAddress1() {
return Address1;
}
public String getAddress2() {
return Address2;
}
public String getCity() {
return City;
}
public String getState() {
return State;
}
public String getCountry() {
return Country;
}
public String getCounty() {
return County;
}
public String getPIN() {
return PIN;
}
}
JSON PARSER CLASS
JSON解析器类
public class parser_Json {
public static JSONObject getJSONfromURL(String url) {
// initialize
InputStream is = null;
String result = "";
JSONObject jObject = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObject = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jObject;
}
}
You can get more info from this question : Get the particular address using latitude and longitude
您可以从这个问题中获得更多信息:使用纬度和经度获取特定的地址
#3
11
Try this
试试这个
List<Address> list = geoCoder.getFromLocation(location
.getLatitude(), location.getLongitude(), 1);
if (list != null & list.size() > 0) {
Address address = list.get(0);
result = address.getLocality();
return result;
#4
7
try below code hope use full for you:-
尝试下面的代码希望您使用充分:-
CityAsyncTask cst = new CityAsyncTask(HomeScreenUserLocation.this,
latitude, longitude);
cst.execute();
String lo = null;
try {
lo = cst.get().toString();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and AsyncTask
和AsyncTask
public class CityAsyncTask extends AsyncTask<String, String, String> {
Activity act;
double latitude;
double longitude;
public CityAsyncTask(Activity act, double latitude, double longitude) {
// TODO Auto-generated constructor stub
this.act = act;
this.latitude = latitude;
this.longitude = longitude;
}
@Override
protected String doInBackground(String... params) {
String result = "";
Geocoder geocoder = new Geocoder(act, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(latitude,
longitude, 1);
Log.e("Addresses", "-->" + addresses);
result = addresses.get(0).toString();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
#5
2
Please refer below code
请参考下面代码
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
String cityName = addresses.get(0).getAddressLine(0);
String stateName = addresses.get(0).getAddressLine(1);
String countryName = addresses.get(0).getAddressLine(2);
#6
2
Try this
试试这个
var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);
geocoder.geocode(
{'latLng': latlng},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add= results[0].formatted_address ;
var value=add.split(",");
count=value.length;
country=value[count-1];
state=value[count-2];
city=value[count-3];
alert("city name is: " + city);
}
else {
alert("address not found");
}
}
else {
alert("Geocoder failed due to: " + status);
}
}
);
);
#7
2
Just Use this method and pass your lat, long.
就用这个方法,把你的腰传过去。
public static void getAddress(Context context, double LATITUDE, double LONGITUDE) {
//Set Address
try {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL
Log.d(TAG, "getAddress: address" + address);
Log.d(TAG, "getAddress: city" + city);
Log.d(TAG, "getAddress: state" + state);
Log.d(TAG, "getAddress: postalCode" + postalCode);
Log.d(TAG, "getAddress: knownName" + knownName);
}
} catch (IOException e) {
e.printStackTrace();
}
return;
}
#8
0
private class MatchingNearByLocationTask extends
AsyncTask<Void, Void, Void>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
progressDialog = new ProgressDialog(mContext);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(true);
progressDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
jsonStr = getLocationInfo(Latitude, Longitude).toString();
if (jsonStr != null) {
Log.i("location--??", jsonStr);
JSONObject jsonObj;
try {
jsonObj = new JSONObject(jsonStr);
String Status = jsonObj.getString("status");
if (Status.equalsIgnoreCase("OK")) {
JSONArray Results = jsonObj.getJSONArray("results");
JSONObject zero = Results.getJSONObject(0);
JSONArray address_components = zero
.getJSONArray("address_components");
for (int i = 0; i < address_components.length(); i++) {
JSONObject zero2 = address_components
.getJSONObject(i);
String long_name = zero2.getString("long_name");
JSONArray mtypes = zero2.getJSONArray("types");
String Type = mtypes.getString(0);
if (Type.equalsIgnoreCase("administrative_area_level_2")) {
// Address2 = Address2 + long_name + ", ";
String City = long_name;
Log.d(" CityName --->", City + "");
}
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
@Override
protected void onCancelled() {
super.onCancelled();
progressDialog.dismiss();
}
}
private JSONObject getLocationInfo(double lat, double lng) {
HttpGet httpGet = new HttpGet(
"http://maps.googleapis.com/maps/api/geocode/json?latlng="
+ lat + "," + lng + "&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
#9
0
You can use this if you have a list:
如果你有一个列表,你可以使用它:
Address address = list.get(0);
String cityname = address.getLocality();
#10
0
com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(data);
if("OK".equals(jsonObject.getString("status"))){
String formatted_address;
JSONArray results = jsonObject.getJSONArray("results");
if(results != null && results.size() > 0){
com.alibaba.fastjson.JSONObject object = results.getJSONObject(0);
String addressComponents = object.getString("address_components");
formatted_address = object.getString("formatted_address");
Log.e("amaya","formatted_address="+formatted_address+"--url="+url);
if(findCity){
boolean finded = false;
JSONArray ac = JSONArray.parseArray(addressComponents);
if(ac != null && ac.size() > 0){
for(int i=0;i<ac.size();i++){
com.alibaba.fastjson.JSONObject jo = ac.getJSONObject(i);
JSONArray types = jo.getJSONArray("types");
if(types != null && types.size() > 0){
for(int j=0;j<ac.size();j++){
String string = types.getString(i);
if("administrative_area_level_1".equals(string)){
finded = true;
break;
}
}
}
if(finded) break;
}
}
Log.e("amaya","city="+formatted_address);
}else{
Log.e("amaya","poiName="+hotspotPoi.getPoi_name()+"--"+hotspotPoi);
}
if(hotspotPoi != null) hotspotPoi.setPoi_name(formatted_address);
EventBus.getDefault().post(new AmayaEvent.GeoEvent(hotspotPoi));
}
}
this is a method to parse google feedback data.
这是一种解析谷歌反馈数据的方法。
#11
0
I got new way to resolve this issue. Here I have used google http service to get total information of location based on longitude and latitude. You just need to pass latitude and longitude in url and your api key (ex : latlng=21.1497409, 79.08747970000002 & key=YOUR API KEY). Here is my get service in ExampleService
Class
我找到了解决这个问题的新方法。这里我使用了谷歌http服务来获取基于经度和纬度的位置信息。您只需在url和api密匙中传递纬度和经度(例如:latlng=21.1497409, 79.08747970000002 & key=您的api密匙)。这是我在考试中得到的服务
getService(url) {
return this.http.get(url).map((data: any) => data.json())
}
this you can put anywhere you want and just call below service from component where you need location data
你可以把它放到你想要的任何地方,然后从需要位置数据的组件调用下面的服务。
this._exampleService.getService("https://maps.googleapis.com/maps/api/geocode/json?latlng=21.1497409, 79.08747970000002&key=YOUR API KEY").subscribe(getplaceData => {
var placeDataDest: any;
placeDataDest = getplaceData;
console.log("i got place id yeee " + placeDataDest['results'][0]['place_id']);
console.log("i got place details yeee " + placeDataDest['results']);
});
similarly find city name....hope you will find this useful
同样....找到城市的名字希望您能发现这一点
#12
0
try using this api :
尝试使用这个api:
URL ": http://maps.googleapis.com/maps/api/geocode/json?latlng="+String.valueOf(yout_lattitude)+","+String.valueOf(your_longitude)
URL:http://maps.googleapis.com/maps/api/geocode/json?latlng= " + String.valueOf(yout_lattitude)+”、“+ String.valueOf(your_longitude)
#13
0
Working code:
工作代码:
addresses = geocoder.getFromLocation(mMap.getCameraPosition().target.latitude, mMap.getCameraPosition().target.longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
String locality = addresses.get(0).getLocality(); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String subLocality = addresses.get(0).getSubLocality(); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
//String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String address1 = addresses.get(0).getAddressLine(1); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String address2 = addresses.get(0).getAddressLine(2); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
// String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
#14
0
import org.json.JSONObject
fun parseLocation(response: String): GeoLocation? {
val geoCodes by lazy { doubleArrayOf(0.0, 0.0) }
val jObj = JSONObject(response)
if (jObj.has(KEY_RESULTS)) {
val jArrResults = jObj.getJSONArray(KEY_RESULTS)
for (i in 0 until jArrResults.length()) {
val jObjResult = jArrResults.getJSONObject(i)
//getting latitude and longitude
if (jObjResult.has(KEY_GEOMETRY)) {
val jObjGeometry = jObjResult.getJSONObject(KEY_GEOMETRY)
if (jObjGeometry.has(KEY_LOCATION)) {
val jObjLocation = jObjGeometry.getJSONObject(KEY_LOCATION)
if (jObjLocation.has(KEY_LAT)) {
geoCodes[0] = jObjLocation.getDouble(KEY_LAT)
}
if (jObjLocation.has(KEY_LNG)) {
geoCodes[1] = jObjLocation.getDouble(KEY_LNG)
}
}
}
var administrativeAreaLevel1: String? = null
//getting city
if (jObjResult.has(KEY_ADDRESS_COMPONENTS)) {
val jArrAddressComponents = jObjResult.getJSONArray(KEY_ADDRESS_COMPONENTS)
for (i in 0 until jArrAddressComponents.length()) {
val jObjAddressComponents = jArrAddressComponents.getJSONObject(i)
if (jObjAddressComponents.has(KEY_TYPES)) {
val jArrTypes = jObjAddressComponents.getJSONArray(KEY_TYPES)
for (j in 0 until jArrTypes.length()) {
when (jArrTypes.getString(j)) {
VALUE_LOCALITY, VALUE_POSTAL_TOWN -> {
return GeoLocation(jObjAddressComponents.getString(KEY_LONG_NAME), *geoCodes)
}
ADMINISTRATIVE_AREA_LEVEL_1 -> {
administrativeAreaLevel1 = jObjAddressComponents.getString(KEY_LONG_NAME)
}
else -> {
}
}
}
}
}
for (i in 0 until jArrAddressComponents.length()) {
val jObjAddressComponents = jArrAddressComponents.getJSONObject(i)
if (jObjAddressComponents.has(KEY_TYPES)) {
val jArrTypes = jObjAddressComponents.getJSONArray(KEY_TYPES)
val typeList = ArrayList<String>()
for (j in 0 until jArrTypes.length()) {
typeList.add(jArrTypes.getString(j))
}
if (typeList.contains(VALUE_SUBLOCALITY)) {
var hasSubLocalityLevel = false
typeList.forEach { type ->
if (type.contains(VALUE_SUBLOCALITY_LEVEL)) {
hasSubLocalityLevel = true
if (type == VALUE_SUBLOCALITY_LEVEL_1) {
return GeoLocation(jObjAddressComponents.getString(KEY_LONG_NAME), *geoCodes)
}
}
}
if (!hasSubLocalityLevel) {
return GeoLocation(jObjAddressComponents.getString(KEY_LONG_NAME), *geoCodes)
}
}
}
}
}
if (geoCodes.isNotEmpty()) return GeoLocation(administrativeAreaLevel1, geoCodes = *geoCodes)
}
}
return null
}
data class GeoLocation(val latitude: Double = 0.0, val longitude: Double = 0.0, val city: String? = null) : Parcelable {
constructor(city: String? = null, vararg geoCodes: Double) : this(geoCodes[0], geoCodes[1], city)
constructor(source: Parcel) : this(source.readDouble(), source.readDouble(), source.readString())
companion object {
@JvmField
val CREATOR = object : Parcelable.Creator<GeoLocation> {
override fun createFromParcel(source: Parcel) = GeoLocation(source)
override fun newArray(size: Int): Array<GeoLocation?> = arrayOfNulls(size)
}
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeDouble(latitude)
dest.writeDouble(longitude)
dest.writeString(city)
}
override fun describeContents() = 0
}