search location name in google map - java

I tried to search location name in google map activity.here in onsearch method address.getLatitude() and address.getLongitude are not work.its show red text.anyone please solve my error. below my code
public void onSearch(View view)
{
EditText location_tf = (EditText)findViewById(R.id.TFaddress);
String location = location_tf.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(0,0);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}

It seems that, you have either imported the wrong Address class or not imported at all. The class which you are looking for can be imported using following line:
import android.location.Address;
The above class contains getLatitude() and getLongitude() methods. Another package which also contains Address class, which I guess, by mistake you imported is following:
com.google.android.gms.identity.intents

Related

DistanceTo Crashes application when running [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm trying to get the difference between 2 locations of which i have taken from the gps, Whenever i click on a button to go to my MapsActivity i get crashed with this error
Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
And When i comment the code which checks difference in distance it works just fine, i don't understand the connection between the Marker options and the DistanceTo
Here's my Code (Keep in mind that all works fine it's just the DistanceTo which doesn't work)
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//get the latitude and longitude from the location
double latitude = location.getLatitude();
double longitude = location.getLongitude();
//get the location name from latitude and longitude
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
if(location != null)
// this gives address list from the maps, not important and commented
{
List<Address> addresses =
geocoder.getFromLocation(latitude, longitude, 1);
// Marker options where the issue occurs
//String result = addresses.get(0).getSubLocality()+":";
//result += addresses.get(0).getLocality()+":";
// result += addresses.get(0).getCountryCode();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker Title"));
mMap.setMaxZoomPreference(20);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
} catch (IOException e) {
e.printStackTrace();
}
//Where it checks for the locations and the distance between them
if(LocationA == null) {
LocationA = location;
}
LocationB = location;
LocationA = LocationB;
DiffernceInDistance = LocationA.distanceTo(LocationB);
}
Code where i made the Map
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
The issue was that i was asking for locations and also applying a marker at the same time, so markers couldn't load to the location, to solve it I commented, It doesn't crash anymore but it didn't solve my main issue (DistanceTo not working but that's not the reason i made this post therefore i won't ask for anymore help thanks )
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker Title"));

how to change marker position on location change in android

I have a Marker on the map and I need to change the position of marker.
Here is my code:
public void onLocationChanged(Location location) {
map.clear();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
if (Home_Activity.this.markerob != null) {
Home_Activity.this.markerob.remove();
markerob.setPosition(latLng);
}
latitude=location.getLatitude();
longitude=location.getLongitude();
CameraUpdate cameraUpdate =CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder().target(new LatLng(location.getLatitude(), location.getLongitude())).zoom(18.0f).build());
MarkerOptions options = new MarkerOptions().position(latLng);
//options.title( getAddressFromLatLng( latLng ) );
options.icon(BitmapDescriptorFactory.fromBitmap(Bitmap.createScaledBitmap(
BitmapFactory.decodeResource(getResources(),
spmain.getavatarimage()), 90, 90, false)));
//map.addMarker(new MarkerOptions().position(latLng));
Toast.makeText(getApplicationContext(), "lat="+latLng,Toast.LENGTH_SHORT).show();
options.position(latLng);
map.getUiSettings().setRotateGesturesEnabled(true);
map.animateCamera(cameraUpdate);
map.moveCamera(cameraUpdate);
map.addMarker(options);
//locationManager.removeUpdates(this);
}
I have added onLocationChanged method and in that, am getting location details but not move the marker on new location.
Check whether your map has marker added on not (for the very first time). If not then add marker and keep the reference to that marker. For subsequent calls to onLocationChanged just use the same reference to update the latitude and longitude.
Marker myMarker;
if(myMarker == null){
marker = map.addMarker(options);
}
else {
marker.setPosition(new LatLng(location.getLatitude(),location.getLongitude()));
}
Hope this helps. Let me know it this does not work. Will post more relevant code.

Android LocationListener- requestLocationUpdates

I try to get my current location. First I created LocationListener:
public LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
myLocation = new LatLng(latitude, longitude);
}
};
The in onCreate method I try to cal requestLocatonUpates on LocationManager:
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,500f,mLocationListener);
But I get an error:
Cannot resolve method requestLocationUpdates(java.langString, long, float,com.google.android.gms.location.LocationListener)
requestLocationUpdates is a method provided in FusedLocationAPi. You should use LocationServices.FusedLocationApi.requestLocationUpdates method.
So you have to create a googleApiClient and a location request.
You can found it here : https://developer.android.com/training/location/index.html.

Make a specific address to a Google Map Marker

I have a google map activity in my app.
I want to enter a specific address of a place, and I want the app to make it to a Google Map Marker.
Until now, I've put a LatLng cod, Like this:
double location_left = Double.parseDouble(leftLocation);
double location_right = Double.parseDouble(rightLocation);
String place_title = child.child("place/place_title").getValue().toString();
LatLng cod = new LatLng(location_left, location_right);
googleMap.addMarker(new MarkerOptions().position(cod).title(place_title));
Is there any option of making a specific address like this "Covert St New york, United States" to a LatLng cod? or to a google maps marker?
Yes using Geocoder API you can convert Address to LatLong List getFromLocationName (String locationName, int maxResults) and Lat-Long to address List getFromLocation(double latitude, double longitude, int maxResults)
This function return Google Map image of input address you can change it to return LatLng
public static String getLocationURLFromAddress(Context context,
String strAddress) {
Geocoder coder = new Geocoder(context);
List<android.location.Address> address;
LatLng p1 = null;
try {
address = coder.getFromLocationName(strAddress, 5);
if (address == null) {
return null;
}
android.location.Address location = address.get(0);
location.getLatitude();
location.getLongitude();
return "http://maps.googleapis.com/maps/api/staticmap?zoom=18&size=560x240&markers=size:mid|color:red|"
+ location.getLatitude()
+ ","
+ location.getLongitude()
+ "&sensor=false";
//
// p1 = new LatLng(location.getLatitude(), location.getLongitude());
} catch (Exception ex) {
ex.printStackTrace();
}
return strAddress;
// return p1;
}
You can directly load image url of Address with the help of Picasso or Glide or if you want to make marker in Map you can do something like this :-
private void addMarker( LatLng currentLatLng ) {
MarkerOptions options = new MarkerOptions();
// following four lines requires 'Google Maps Android API Utility Library'
// https://developers.google.com/maps/documentation/android/utility/
// I have used this to display the time as title for location markers
// you can safely comment the following four lines but for this info
IconGenerator iconFactory = new IconGenerator(this);
iconFactory.setStyle(IconGenerator.STYLE_PURPLE);
options.icon(BitmapDescriptorFactory.fromBitmap(iconFactory.makeIcon(mLastUpdateTime)));
options.anchor(iconFactory.getAnchorU(), iconFactory.getAnchorV());
Marker mapMarker = googleMap.addMarker(options);
long atTime = mCurrentLocation.getTime();
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date(atTime));
mapMarker.setTitle(mLastUpdateTime);
Log.d(TAG, "Marker added.............................");
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng,
13));
Log.d(TAG, "Zoom done.............................");
}

Not able to display path from current location to destination google maps V2

I am trying to draw path from current location to destination using the answer Android: How to draw route directions google maps API V2 from current location to destination.
But in place of the hard coded I longitude and Latitude of the current location I want to use my real location. But whenever I try to do that, the App is crashing with error in line location = mMap.getMyLocation();
Any help is appreciated.
MapsActivity.Java
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
Location location;
LatLng myPosition;
GMapV2Direction md;
LatLng fromPosition = getYourLocation();
LatLng toPosition = new LatLng(13.683660045847258, 100.53900808095932);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
md = new GMapV2Direction();
setUpMapIfNeeded();
LatLng coordinates = new LatLng(13.685400079263206, 100.537133384495975);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 16));
mMap.addMarker(new MarkerOptions().position(fromPosition).title("Start"));
mMap.addMarker(new MarkerOptions().position(toPosition).title("End"));
Document doc = md.getDocument(fromPosition, toPosition, GMapV2Direction.MODE_DRIVING);
int duration = md.getDurationValue(doc);
String distance = md.getDistanceText(doc);
String start_address = md.getStartAddress(doc);
String copy_right = md.getCopyRights(doc);
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);
for(int i = 0 ; i < directionPoint.size() ; i++) {
rectLine.add(directionPoint.get(i));
}
mMap.addPolyline(rectLine);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
/*myPosition = getLocation();
ZoomCurrentLocation(myPosition);*/
}
}
}
private LatLng getYourLocation() {
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
double latitude = 0;
double longitude = 0;
if (location != null) {
// Getting latitude of the current location
latitude = location.getLatitude();
// Getting longitude of the current location
longitude = location.getLongitude();
// Creating a LatLng object for the current location
}
LatLng latLng = new LatLng(latitude, longitude);
return latLng;
}
private void ZoomCurrentLocation(LatLng myPosition)
{
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myPosition, 16));
}
private void setUpMap(LatLng myPosition) {
mMap.addMarker(new MarkerOptions().position(myPosition).title("Marker"));
}
}
Do you mean location = mMap.getMyLocation(); is the method getYourLocation() in the code, and the crash is at Location location = locationManager.getLastKnownLocation(provider); ?
If so, it may cause by NullPointer Exception, you need use new api FusedLocationApi to avoid getLastLocation null pointer.
Please check here to know how to use it. And here is the code for it on my github.
For the destination you can check here to get some idea.

Categories