Cannot zoom above whole country, java Google Maps V2 - java

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);
}
});

Related

Android refresh google map after turning on location

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
}
[...]

Google Map driving directions between two locations in my own application

I was working on Google maps, I need Google map driving direction between two locations(my current location and destination location) in my own application I don't want to open any google maps application. so please suggest me how to do this. up to now i have completed integrating google maps, zoom to my current location, placing a marker in destination lat-long.
my java file:
public class GoogleMapActivity extends FragmentActivity implements
OnMapReadyCallback, GoogleMap.OnMarkerClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
Location mLastLocation;
GoogleApiClient mGoogleApiClient;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_map);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Log.d("Tag", "in onc control in try");
buildGoogleApiClient();
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
Log.d("TAG","lat"+mLastLocation.getLatitude());
Log.d("TAG","lng"+mLastLocation.getLongitude());
ToastHelper.blueToast(getApplicationContext(), "location is " + mLastLocation.getLatitude() + " " + mLastLocation.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()), 12.0f));
LatLng destination = new LatLng(14.880499, 79.988847);
mMap.addMarker(new MarkerOptions().position(destination).title("Destination"));
}
else {
Log.d("TAG","mLastLocation is null");
}
}
#Override
public void onConnectionSuspended(int i) {
}
/**
* Called when the map is ready.
*/
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
}
/**
* Called when the user clicks a marker.
*/
#Override
public boolean onMarkerClick(final Marker marker) {
// Retrieve the data from the marker.
// Return false to indicate that we have not consumed the event and that we wish
// for the default behavior to occur (which is for the camera to move such that the
// marker is centered and for the marker's info window to open, if it has one).
return false;
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
There is a webservice public API for directions by google. It is not bundled with android API as far as I know.
Here you go with the link which will get you started
Check out this Awesome and easy to use Library:
https://github.com/jd-alexander/Google-Directions-Android
This library allows you to calculate the route between two locations
and displays it on a map.
It provides you a list of routing point which you can plot in Google Map to show routes and directions.
I don't know the end goal of your project. But if your intention is to get directions from point A to point B. Google's Roads Api can provide you with the data you need to draw the directions on a map or whatever you want.
It provides you the raw points even the speed in that particular road segment. It takes care of the redundant data that might lead you to draw directions through buildings for instance.
Finally got the result:
use this API link:
http://maps.googleapis.com/maps/api/directions/json?origin=(origin)&destination=(destination)
where it will return JSON as a response which contains latitudes and longitudes,
and store them in an array and draw polylines using those lat-long points in google maps

Location updates not showing for GPS

I'm trying to retrieve the device's current location using the device's GPS. When I register for updates (as shown below) for LocationManager.GPS_PROVIDER no updates are rolling, yet when I do the same for LocationManager.NETWORK_PROVIDER I get the updates.
I have tested it on my Android device (not the emulator). I have also made sure the GPS is on. Other apps (not mine) are able to access my location. What am I missing here?
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
locationRetrieved(location, this);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) { }
public void onProviderDisabled(String provider) { providerDisabled(); }
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
GPS start up is not an instant process. The receiver basically has to know the position of each of the GPS satellites in the constellation in order to calculate it's location
Are you first checking if there is a last known location which you can use? Most apps first check for it and then search for a location.
You should check wheter your phone is allowing the gathering of location with GPS.
Probabily what is happening is that in Settings -> Location you only have the checkbox for wireless location. If so, the GPS_PROVIDER doesn't work.

How can I check wether a (Google maps API) map has loaded?

I have started building an android application that focuses on a map from google-play-services-libs. When I start the app, it takes a while for the map to load from the gray grid to showing the map image.
I'd like to move/play around a bit with the map when it has fully loaded the part that is currently on screen. I have however been unable to find a way to programmatically check whether the map has loaded.
How can I achieve this?
In short:
From a instance of GoogleMap, how do I determine if it is actually showing something?
You can try using a OnCameraChangeListener on your map. The onCameraChange call will be called when the map's tiles are initially loaded.
this.map.setOnCameraChangeListener(new OnCameraChangeListener() {
public void onCameraChange(CameraPosition arg0) {
isMapReady = true;
map.setOnCameraChangeListener(null);
}
});
chckReady() function checks whether the map is ready or not
public class MapView extends android.support.v4.app.FragmentActivity {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ui_settings_demo);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
}
}
private boolean checkReady() {
if (mMap == null) {
return false;
}
}
}

Android locationlistener doesn't work on android device

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.

Categories

Resources