Ive added reverse Geocoding to my map and set the map to clickable. Everything works as it should except the address is not showing above the marker when i click the map.
my latLan is an array but thats the only way it would allow me to use the variable. i think the problem lies around this area but cant put my hand on it.
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); // changes view to hybrid
mMap.setMyLocationEnabled(true); // shows location on map
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); // uses GPS only to get location
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
final LatLng[] latLng = {(new LatLng(currentLatitude, currentLongitude))};
mMap.animateCamera(
CameraUpdateFactory.newLatLngZoom(latLng[0], 18)); // This will zoom camera to updated lat and long without constant updates
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {// Setting a click event handler for the map
#Override
public void onMapClick(LatLng arg0) {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); // uses GPS only to get location
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
//LatLng latLng;
// Getting the Latitude and Longitude of the touched location
latLng[0] = arg0;
// Clears the previously touched position
mMap.clear();
// Animating to the touched position
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng[0]));
// Creating a marker
markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng[0]);
// Placing a marker on the touched position
mMap.addMarker(markerOptions);
// Adding Marker on the touched location with address
new ReverseGeocodingTask(getBaseContext()).execute(latLng[0]);
}
});
//new ReverseGeocodingTask(getBaseContext()).execute(latLng);
}
private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String> {
Context mContext;
public ReverseGeocodingTask(Context context) {
super();
mContext = context;
}
#Override
protected String doInBackground(LatLng... params) {
Geocoder geocoder = new Geocoder(mContext);
double latitude = params[0].latitude;
double longitude = params[0].longitude;
List<android.location.Address> addresses = null;
String addressText = "";
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
android.location.Address address = addresses.get(0);
addressText = String.format("%s, %s, %s", address.getMaxAddressLineIndex() > 0 ?
address.getAddressLine(0) : "", address.getLocality(), address.getCountryName());
}
return addressText;
}
#Override
protected void onPostExecute(String addressText) {
markerOptions.title(addressText);
mMap.addMarker(markerOptions);
}
}
}
Tested your code and found possible cause of error.
// Placing a marker on the touched position
mMap.addMarker(markerOptions);
Upon implementing addMarker() before doing the ReverseGeocodingTask() and calling addMarker() again in the onPostExecute(). You can try adding an custom marker image large enough to make the address and the overwriting marker visible.
Customize the marker image
You can replace the default marker image with a custom marker image, often called an icon. Custom icons are always set as a BitmapDescriptor, and defined using one of four methods in the BitmapDescriptorFactory class.
Code for custom image:
private static final LatLng MELBOURNE = new LatLng(-37.813, 144.962);
private Marker melbourne = mMap.addMarker(new MarkerOptions()
.position(MELBOURNE)
.title("Melbourne")
.snippet("Population: 4,137,400")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)));
You can remove the first mMap.addMarker(markerOptions); before new ReverseGeocodingTask(getBaseContext()).execute(latLng[0]); then it your app will work as it should be.
Use This Code May be work for getting Address
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0) + address.getAddressLine(1) + address.getAddressLine(2) + address.getAddressLine(3);
}
Related
I am trying to display markers on map in android by using address.
This is my code:
public void onMapReady(GoogleMap googleMap){
mMap = googleMap;
Geocoder coder= new Geocoder(this);
try
{
String straddress = "155 Park Theater,Palo Alto,CA";
Double latitude = 0.0;
Double longitude = 0.0;
List<Address> addresses = coder.getFromLocationName("155 Park Theater,Palo Alto,CA",1);
Address location = addresses.get(0);
LatLng p1 = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(p1).title("California"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(p1));
}
catch (Exception e)
{
e.printStackTrace();
}
}
If I do not put street number, then it will display the marker.
But, it will just display marker on the street. I want marker on particular location.
I am getting following error while inputting the whole address with street number. The "address" list is empty.
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
Update your code with following :
List<Address> address;
LatLng latLng = null;
try {
address = coder.getFromLocationName(strAddress,5);
if (address==null) {
return null;
}
Address location=address.get(0);
latLng = new LatLng(location.getLatitude(),location.getLongitude());
}
I am trying to replace mMpap.SetMyPosition(true); function with my own. I had some success on it and when my custom image for "My Position Icon" is tapped, it moves camera to current location with my custom marker.
Everything works fine on it except whenever "My Position Icon" is tapped, it leaves a copy of marker to that position and moves to current location with a new marker.
I am fairly new to Android Development and looking for some help.
My code inside onCreate(Bundle savedInstanceState) is:
ImageView img = (ImageView) findViewById(R.id.myPostionButton);
img.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getTheLocation();
}
});
And getTheLocation() is:
if (location != null) {
final double latitude = location.getLatitude();
final double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
final Marker marker = mMap.addMarker(
new MarkerOptions()
.position(new LatLng(latitude, longitude))
.draggable(true)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_marker)));
mMap.setTrafficEnabled(true);
mMap.setMinZoomPreference(10.0f);
mMap.setMaxZoomPreference(20.0f);
//mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16.0f),4000 , null);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16.0f));
mMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
#Override
public void onCameraMove() {
LatLng centerOfMap = mMap.getCameraPosition().target;
marker.setPosition(centerOfMap);
}
});
mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
LatLng centerOfMap = mMap.getCameraPosition().target;
marker.setPosition(centerOfMap);
double latitude = centerOfMap.latitude;
double longitude = centerOfMap.longitude;
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
String str = addressList.get(0).getAddressLine(0) + ", ";
str += addressList.get(0).getSubLocality() + ", ";
str += addressList.get(0).getLocality() + ", ";
str += addressList.get(0).getCountryCode();
mFromAddress.setText(str);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
And onMapReady(GoogleMap googleMap) is:
mMap = googleMap;
getTheLocation();
Please Help.
You can try any one of the following based on your situation:
1. If you have only one marker in map, before adding the new marker, clear the map using mMap.clear();
2. If you have multiple markers then you have to keep your current marker object as member variable mMarker. Then just before adding the new marker you can use mMarker.remove();.
I am developing an android google map application, that is showing current location on map starting.
I have an search bar in the application, when user enter any area name, then the second marker will be placed on that location.
Now my problem is, how to get second marker longitude and latitude position and make a route between the two markers.
my MainActivity.java code as follows:
public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
public void onMapSearch(View view) {
EditText locationSearch = (EditText) findViewById(R.id.editText);
String location = locationSearch.getText().toString();
List<Address> addressList = null;
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(27.746974, 85.301582);
mMap.addMarker(new MarkerOptions().position(sydney).title("Kathmandu, Nepal"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
// Enable MyLocation Button in the Map
mMap.setMyLocationEnabled(true);
}
}
Please Help me.
In your program you have used the code to get the LatLng of the second marker.
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
To make a polyline, refer to this link. By the this question has already been answered.
https://www.simplifiedcoding.net/google-maps-distance-calculator-google-maps-api/
Set Google Places API for search EdiText. Get the value from that and pass it as address..
Here is the code(address denoting strAddress here)
List<Address> address = null;
Geocoder coder = new Geocoder(getApplicationContext());
try {
address = coder.getFromLocationName(strAddress, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (address != null) {
Address location = address.get(0);
double lat = location.getLatitude();
double log = location.getLongitude();
}
I am working on an Android application and Google Maps in which I am searching for the particular address by using the following code. I want to get the location of the searched address if it is in 100km within my location, and if it outside that limit, it will not show me.
I am trying to get the searched location within my 100km radius.
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{
#Override
protected List<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
//
//24.798406, 54.790448
//25.452403, 55.537519
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 10,
24.861969, 54.857740,25.545368, 55.474347);//.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
}
// Clears all the existing markers on the map
mMap.clear();
// Adding Markers on Google Map for each matching address
for(int i=0;i<addresses.size();i++){
Address address = (Address) addresses.get(i);
LatLng latLng;
// Creating an instance of GeoPoint, to display in Google Map
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
// markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.flag));
markerOptions.title(addressText);
mMap.addMarker(markerOptions);
// Locate the first location
if(i==0)
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}
You can calculate distance using this code; here, distance is in meters. You can call this function and check where the location is in the range or not.
private boolean checkForArea(int rad, LatLng fromPosition, LatLng toPosition) {
Location locationA = new Location("point A");
locationA.setLatitude(fromPosition.latitude);
locationA.setLongitude(fromPosition.longitude);
Location locationB = new Location("point B");
locationB.setLatitude(toPosition.latitude);
locationB.setLongitude(toPosition.longitude);
int distance = (int) locationA.distanceTo(locationB);
if (distance / 1000 <= rad)
return true;
else
return false;
}
I tried some code to make Geocoding reverse location (using Google Maps Android API v2) and show title with marker, but the marker title didn't showed when I run my application.
Here is my code :
public class MainActivity extends FragmentActivity {
GoogleMap googleMap;
MarkerOptions markerOptions;
LatLng latLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
// Getting a reference to the map
googleMap = supportMapFragment.getMap();
// Setting a click event handler for the map
googleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng arg0) {
// Getting the Latitude and Longitude of the touched location
latLng = arg0;
// Clears the previously touched position
googleMap.clear();
// Animating to the touched position
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Creating a marker
markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
// Adding Marker on the touched location with address
new ReverseGeocodingTask(getBaseContext()).execute(latLng);
}
});
}
private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String>{
Context mContext;
public ReverseGeocodingTask(Context context){
super();
mContext = context;
}
// Finding address using reverse geocoding
#Override
protected String doInBackground(LatLng... params) {
Geocoder geocoder = new Geocoder(mContext);
double latitude = params[0].latitude;
double longitude = params[0].longitude;
List<Address> addresses = null;
String addressText="";
try {
addresses = geocoder.getFromLocation(latitude, longitude,1);
} catch (IOException e) {
e.printStackTrace();
}
if(addresses != null && addresses.size() > 0 ){
Address address = addresses.get(0);
addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
}
return addressText;
}
#Override
protected void onPostExecute(String addressText) {
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(addressText);
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
}
}
}
Is there a problem with my code ?
change your code in onPostExecute()
googleMap
.addMarker(
new MarkerOptions()
.position(loc)
.draggable(true)
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.title(addressText))
.showInfoWindow();
Try this
public class MainActivity extends FragmentActivity {
GoogleMap googleMap;
MarkerOptions markerOptions;
LatLng latLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
// Getting a reference to the map
googleMap = supportMapFragment.getMap();
// Setting a click event handler for the map
googleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng arg0) {
// Getting the Latitude and Longitude of the touched location
latLng = arg0;
// Clears the previously touched position
googleMap.clear();
// Animating to the touched position
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Creating a marker
markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
// Adding Marker on the touched location with address
new GetAddressTask().execute(latLng);
// new ReverseGeocodingTask(MainActivity.this).execute(latLng);
}
});
}
public class GetAddressTask extends AsyncTask<LatLng, Void, Integer>{
private LatLng loc;
String addressText;
#Override
protected Integer doInBackground(LatLng... params) {
int mFinalFlag=0;
loc=params[0];
String filterAddress = "";
Geocoder geoCoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(loc.latitude,
loc.longitude, 1);
if (addresses!=null&&addresses.size() > 0) {
Address address = addresses.get(0);
addressText = String.format(
"%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
}
} catch (IOException ex) {
} catch (Exception e2) {
e2.printStackTrace();
}
return mFinalFlag;
}
}
#Override
protected void onPostExecute(Integer result) {
googleMap.addMarker(
new MarkerOptions()
.position(loc)
.draggable(true)
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.title(addressText))
.showInfoWindow();
super.onPostExecute(result);
}
}