我在 Android 应用程序中添加了地图,并想按地址在地图上添加标记。有可能的?
我已经尝试过做长和拉Geocoder
,但是我收到错误Service not Available
.
my code:
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocationName(event.getPlace(), 20);
System.out.println(addresses);
// for (int i = 0; i < addresses.size(); i++) { // MULTIPLE MATCHES
//
// Address addr = addresses.get(i);
//
// double latitude = addr.getLatitude();
// double longitude = addr.getLongitude(); // DO SOMETHING WITH
// // VALUES
//
// System.out.println(latitude);
// System.out.println(longitude);
//
// }
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
创建一个将地址转换为 LatLng 的方法:
public LatLng getLocationFromAddress(Context context, String strAddress)
{
Geocoder coder= new Geocoder(context);
List<Address> address;
LatLng p1 = null;
try
{
address = coder.getFromLocationName(strAddress, 5);
if(address==null)
{
return null;
}
Address location = address.get(0);
location.getLatitude();
location.getLongitude();
p1 = new LatLng(location.getLatitude(), location.getLongitude());
}
catch (Exception e)
{
e.printStackTrace();
}
return p1;
}
then ,
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng address = getLocationFromAddress(this, yourAddressString(eg. "Street Number, Street, Suburb, State, Postcode");
mMap.addMarker(new MarkerOptions().position(address).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(address));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)