我有一個功能geoLocate()
找到用戶輸入的位置。我希望這個功能能夠找到用戶當前位置附近的位置。誰能幫忙?查找附近的地方
當我打電話geoLocate("McDonald's")
時,我希望它找到與用戶位置相關的最近麥當勞。
public void geoLocate(String searchString) throws IOException {
Geocoder gc = new Geocoder(this);
List<Address> list = gc.getFromLocationName(searchString, 3);
if (list.size() > 0) {
android.location.Address add = list.get(0);
String locality = add.getLocality();
Toast.makeText(this, "Found: " + locality, Toast.LENGTH_SHORT).show();
double lat = add.getLatitude();
double lng = add.getLongitude();
gotoLocation(lat, lng, 17);
if (marker != null) {
marker.remove();
}
MarkerOptions options = new MarkerOptions().title(locality).position(new LatLng(lat, lng));
marker = mMap.addMarker(options);
} else {
Toast.makeText(this, "No results found for: " + searchString, Toast.LENGTH_LONG).show();
}
}
查找當前位置以供參考:
public void setCurrentLocation() {
try {
Location currentLocation = LocationServices.FusedLocationApi.getLastLocation(mLocationClient);
if (currentLocation == null) {
Toast.makeText(this, "Couldn't connect!", Toast.LENGTH_SHORT).show();
} else {
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, 15);
mMap.animateCamera(update);
if (myLocationMarker != null) {
myLocationMarker.remove();
}
MarkerOptions options = new MarkerOptions().title(currentLocation.getLatitude() +
", " + currentLocation.getLongitude()).position(latLng);
myLocationMarker = mMap.addMarker(options);
}
} catch (SecurityException e) {
e.printStackTrace();
Toast.makeText(this, "My Location not enabled!", Toast.LENGTH_SHORT).show();
}
}