I have a google map in my project. First of all, I check whether the user has location enabled. If the user does not have location enabled, a dialog box pops up asking them to enable location. When the user accepts this prompt, he or she is redirected to the settings page where they can enable location.
The problem is after enabling location and press back, the map remains in its previous state, i.e. does not zoom to the user's current location.
How can I solve this?
I think you should reload the map on the method onResume:
edit (i am assuming that you have declared the mGoogleMap object on class scope):
GoogleMap googleMap;
#Override
public void onResume() {
super.onResume();
if(googleMap != null){
googleMap.clear();
// add the markers just like how you did the first time
}
}
You have to implement LocationListener
public class FragmentMap extends SupportMapFragment implements LocationListener
{
GoogleMap mGoogleMap_;
[...]
#Override
public void onLocationChanged(Location location)
{ CameraPosition.Builder builder = CameraPosition.builder(mGoogleMap_.getCameraPosition());
builder.target(new LatLng(location.getLatitude(), location.getLongitude()));
mGoogleMap_.animateCamera(CameraUpdateFactory.newCameraPosition(builder.build())); // CameraUpdateFactory.newLatLngZoom(...) if you need to zoom too
}
[...]
Related
I would like to trigger the onMapClick() action on my map by pressing a button and sending it the required parameter. The following is run whenever the map is touched:
#Override
public void onMapClick(LatLng point) {
// animate camera to centre on touched position
mMap.animateCamera(CameraUpdateFactory.newLatLng(point));
// Adding new latlng point to the array list
markerPoints.add(point);
// Creating MarkerOptions object
MarkerOptions marker = new MarkerOptions();
// Sets the location for the marker to the touched point
marker.position(point);
}
I would like this button to replicate the same action as touching the screen except I am manually passing in a value:
mButtonCompleteLoop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onMapClick(markerPoints.get(0));
}
});
An error is appearing saying that onMapClick() cannot be resolved. Is there a certain way to do this? Or is it better to extract the onMapClick() code into a separate method that can then be called from both?
It is difficult to guess about reasons without looking on whole code of your activity/fragment
Maybe you set your map listener as anonymous class.
If so, instead of:
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
//this
}
});
You should make your activity implements GoogleMap.OnMapClickListener and set listener like this
mMap.setOnMapClickListener(this);
Then you can call OnMapClick from any place
I am developing a project with a map displaying 100 markers in a country (Greece). When my map is open while launching application in my mobile android phone, map zooms in Africa and in a tablet device it zooms in different location- country. This happens when my location is disabled through settings of my device. How can I set the map to zoom above whole country Greece when my map is loaded for first time? in any android device application is installed?
Please check my code below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Check mMap. In case it is not null then setUpMap
*/
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) {
setUpMap();
}
}
}
When I activate current location then it zooms on level 14 over my location. I need to keep this functionality when location setting are enabled.
// Show the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
You can do:
map.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(xxxx,xxxx) , 14.0f) );
Where the coords, are for example the "middle" of Greece. And you will need to set some SharedPreference to know if is the first time that the app is open.
You can use the new version of API that calls you when the map is loaded:
http://developer.android.com/reference/com/google/android/gms/maps/GoogleMap.OnMapLoadedCallback.html
You can easily check if it is the first time by using a simple "singleton" or static variable.
About the Zoom, I would recomend you to build a LatLngBounds and zoom on it.
You can do this by iterating over all the Markers:
LatLngBounds.Builder zoomTo = LatLngBounds.builder();
for (Marker marker : markersList) {
zoomTo.include(marker.getPosition());
}
final LatLngBounds workArea = zoomTo.build();
mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(workArea, 50));
mMap.setOnMapLoadedCallback(null);
}
});
Doing an Application whcoh displays Markers on a Google Maps Fragment and opens a link in a browser on click, but i have a single marker where i dont want this to happen.
GoogleMap mMap;
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.fragment1)).getMap();
mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat3, lng3))
.snippet(bud1)
.title(name1));
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Uri uriUrl = Uri.parse(pcurl1);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
});
Now i want to implement a if (.... != "Your Position") in the onInfoWindowClick() but I have no Idea how to check the Marker for this content inside the marker.
Edit: New Problem occured which is "Cannot refer to a non-final variable pcurl1 inside an inner class defined in a different method" and if I set it final it destroys it's funktion becasue it is set inside a loop.
addMarker method returns a Marker object. For your location marker, save if as a field e.g. myLocationMarker and in the callback do
if (!marker.equals(myLocationMarker)) {
// ...
Everything seems to be working fine. It can find my location, but it won't call the onLocationChanged() method and create a marker for me. Any ideas?
public class MainActivity extends FragmentActivity implements LocationListener
{
Context context = this;
GoogleMap googlemap;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initMap();
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
String provider = lm.getBestProvider(new Criteria(), true);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100, 0, this);
}
public void onLocationChanged(Location location) {
LatLng current = new LatLng(location.getLatitude(), location.getLatitude());
Date date = new Date();
googlemap.addMarker(new MarkerOptions()
.title("Current Pos")
.snippet(new Timestamp(date.getTime()).toString())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
.position(current)
);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
private void initMap(){
SupportMapFragment mf = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googlemap = mf.getMap();
googlemap.setMyLocationEnabled(true);
googlemap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
}
Your Activity needs to implement the LocationSource interface, and you need to register your GoogleMap to use the MainActivity class as its location source:
Change your class declaration to:
public class MainActivity extends FragmentActivity implements LocationListener, LocationSource
And set the GoogleMap's LocationSource
//This is how you register the LocationSource for the map
googleMap.setLocationSource(this);
See this answer for more a complete example.
Do you have wifi turned on? Everything seems to be well defined.
Maybe your wifi signal is weak and you're having connection problems? Try getting location updates through the GPS provider:
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 0, this);
In fact, I always include both so that the user can get his location from either provider. Also, try including a log statement in your onLocationChanged callback. If it turns out that method is in fact being called, then you know your problem is with adding the marker, not your location retrieval.
My location listener works when I am using the DDMS controls in the emulator but when I deploy it onto the phone it no longer works. My code is as follows
public class hoosheerAndroidAct extends MapActivity implements LocationListener {
/** Called when the activity is first created. */
MapController mc;
public static MapView gMapView = null;
GeoPoint p = null;
static double latitude, longitude;
MyLocationOverlay myLocationOverlay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen1);
// Creating and initializing Map
gMapView = (MapView) findViewById(R.id.mapview);
p = new GeoPoint((int) (latitude * 1E6),
(int) (longitude * 1E6));
gMapView.setSatellite(true);
gMapView.setBuiltInZoomControls(true);
mc = gMapView.getController();
mc.setCenter(p);
mc.setZoom(11);
myLocationOverlay = new MyLocationOverlay(this, gMapView);
gMapView.getOverlays().add(myLocationOverlay);
list = gMapView.getOverlays();
list.add(myLocationOverlay);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 5.0f,
this);
}
methods implemented for implements LocationListener
public void onLocationChanged(Location location) {
if (location != null) {
GeoPoint point = new GeoPoint((int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
mc.animateTo(point);
connect("http://api.foursquare.com/v1/venues.json?geolat="
+ location.getLatitude() + "&geolong="
+ location.getLongitude());
Drawable marker = getResources().getDrawable(R.drawable.marker);
gMapView.getOverlays().add(new SitesOverlay(marker));
}
}
public void onProviderDisabled(String provider) {
// required for interface, not used
}
public void onProviderEnabled(String provider) {
// required for interface, not used
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// required for interface, not used
}
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
Is there anything I am missing? :-(
Google maps will default to network location provider if the GPS is unable to find a signal so that test could return a location without a GPS signal. I would recommend GPS Status as a good free app. The only other thing I can think of is to make sure you have a clear view of the sky.
its because when your device is not able to find location it return default location 0,0. better you check your device gps connection by checking other apps like map app of your device
Maybe you are testing in door,can't get gps information. try to change LocationManager.GPS_PROVIDER-->LocationManager.NETWORK_PROVIDER.
I had a similar problem and try everything in programming. I read about that google use same other sensors to find location. I even find mobile where location listener won't work in google maps. When I checked the settings i accedently turn on battery power saving and location listener starts. On some other device where location wan't work too I turn on buttery saving and location is shown. I don't know why is that, but buttery maybe will save your app.