Cannot cast form Fragment to Mapfragment - android

i Want to make maps in android, this is for My Skripsi, i Download Source code in here https://github.com/ajaswal/GoogleMapsV2 i strat open project, but have proble this is my problem, i have alert about cannot cast from Fragment to MapFragment, this problem in line 27.
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
so please help me...
package com.example.googlemaps;
import android.app.Activity;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends Activity {
public final LatLng LOCATION_BURNABY= new LatLng(49.27645, -122.917587);
public final LatLng LOCATION_SURREY= new LatLng(49.187500, -122.849000);
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
if (map != null) {
setUpMap();
}
}
private void setUpMap() {
// Enable MyLocation layer of Google map
map.setMyLocationEnabled(true);
// Get Location manager object from System service LOCATION_SERVICE
LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locManager.getBestProvider(criteria, true);
// Get current location
Location myLocation = locManager.getLastKnownLocation(provider);
// Set map type
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get the latitude of the current location
double latitude = myLocation.getLatitude();
// Get the longitude of the current location
double longitude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng LOCATION_CURRENT = new LatLng(latitude, longitude);
// Show the current location in Google map
map.moveCamera(CameraUpdateFactory.newLatLng(LOCATION_CURRENT));
// Zoom in the google map
CameraUpdate camUpdate = CameraUpdateFactory.newLatLngZoom(
LOCATION_CURRENT, 15);
map.animateCamera(camUpdate);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick_Burnaby(View v){
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(LOCATION_BURNABY, 13);
map.animateCamera(update);
}
public void onClick_Surrey(View v){
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(LOCATION_SURREY, 14);
map.animateCamera(update);
}}

Use FragmentActivity instead of Activity
Example -
public class MapScreen extends FragmentActivity{
private GoogleMap map;
private Location location;
private ArrayList<LatLng> mLocationsLatLngList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_screen);
map = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.mapfragment)).getMap();
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(Your_CurrentLocation).zoom(13).bearing(0) // Sets the orientation of the camera to east
.tilt(30) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
map.setBuildingsEnabled(true);
map.setMyLocationEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
xml -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment
android:id="#+id/mapfragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
class="com.google.android.gms.maps.SupportMapFragment" />
</LinearLayout>

You are using SupportMapFragment in the XML, so you must use getSupportFragmentManager instead of getFragmentManager.
Use this code to obtain the Fragment and the Map:
SupportMapFragment fr = (SupportMapFragment)this.getSupportFragmentManager().findFragmentById(R.id.mapfragment);
GoogleMap Map = fr.getMap();
Your Activity must extend FragmentActivity.

Related

How do I update the marker within Google Maps? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
In the below code, I am able to create a marker on the map. Whenever I try to run it with the runnable, I get the error stating to googleMap with the error as:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.journaldev.MapsInAction/com.journaldev.MapsInAction.MainActivity}: java.lang.NullPointerException: 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
The code is as follows:
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
SupportMapFragment mapFragment;
private GoogleMap googleMap;
double latitude=12.9716;
double longitude=77.5946;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title("Bus Location")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 15));
}
});
}
});
periodicUpdate.run();
}
Handler handler = new Handler();
private Runnable periodicUpdate = new Runnable() {
#Override
public void run() {
handler.postDelayed(periodicUpdate, 10*1000 - SystemClock.elapsedRealtime()%1000);
latitude+=0.01;
longitude+=0.01;
MarkerOptions a = new MarkerOptions()
.position(new LatLng(50,6));
Marker m = googleMap.addMarker(a);
m.setPosition(new LatLng(50,5));
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onMapReady(GoogleMap googleMap)
{
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title("Bus Location")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 15));
}
}
How do I make sure that the code also updates the marker every 10 seconds? If the Runnable code is removed, it works perfectly with the marker shown. With the Runnable code, it crashes with the error above.
getMapAsync initialize Map asynchronously.
So when you call googleMap.addMarker() at first time in your Runnable it crashes because Map is not initialized yet and googleMap is null.
Easiest way to fix this is move periodicUpdate.run(); to onMapReady() callback
Also you must not forget to clean Runnable in onPause()
You are putting marker before map is initialized in runnable. That is why it is causing null pointer exception and crashing app. Putting a null pointer check will resolve this error. Try this:
#Override
public void run() {
handler.postDelayed(periodicUpdate, 10 * 1000 - SystemClock.elapsedRealtime() % 1000);
latitude += 0.01;
longitude += 0.01;
MarkerOptions a = new MarkerOptions()
.position(new LatLng(50, 6));
if (googleMap != null) {
Marker m = googleMap.addMarker(a);
}
m.setPosition(new LatLng(50, 5));
}
There are several issues with your code.
At first, it crashes because in periodicUpdate.run(); you try to create marker (Marker m = googleMap.addMarker(a);) by calling addMarker() on global private GoogleMap googleMap; object which is not initialized. It will be better if you rename private GoogleMap googleMap; to private GoogleMap mGoogleMap; and init mGoogleMap in onMapReady(GoogleMap googleMap) by mGoogleMap = googleMap nd than call addMarker() on it: Marker mGoogleMap = googleMap.addMarker(a);.
Also, you should get rid of two onMapReady() methods. And you should start call periodicUpdate.run(); inside onMapReady() because in other case its possible that the Marker m = mGoogleMap.addMarker(a); can be called before mGoogleMap was created. And you should declare Marker m as global (private Marker mMarker) for possibility to remove it before create updated marker. And seems you didn't update LatLng of marker... So, there are a lot of work...
You haven't initialed the variable googleMap yet. And before using googleMap, you have to make sure Google Map is ready. So follow this code:
private Runnable periodicUpdate = new Runnable() {
#Override
public void run() {
handler.postDelayed(periodicUpdate, 10*1000 - SystemClock.elapsedRealtime()%1000);
if(googleMap){
latitude+=0.01;
longitude+=0.01;
MarkerOptions a = new MarkerOptions()
.position(new LatLng(50,6));
Marker m = googleMap.addMarker(a);
m.setPosition(new LatLng(50,5));
}
}
};
#Override
public void onMapReady(GoogleMap googleMap)
{
this.googleMap = googleMap;
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title("Bus Location")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 15));
}

Maps API only loads with location setting GPS

I use the Google Maps API in my Android app and locate the user with
LocationManager and getLongitude(), getLatitude().
But now there have to be strange settings on the mobile phone to get a map. The location setting has to be changed to only use GPS, and even then it's not working all the time, sometimes the map is not loaded. If not loaded the app shuts down at the point the first marker is set because of NullPointerException.
Why is this and how can I prevent it?
I already tried with getMapAsync but it didn't help.
GoogleMap googleMap;
LocationManager locationManager;
String provider;
Criteria criteria;
Location myLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
try {
if(googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMyLocationEnabled(true);
googleMap.setTrafficEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
myLocation = locationManager.getLastKnownLocation(provider);
double latitude = myLocation.getLatitude();
double longitude = myLocation.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(14));
iconDone = R.drawable.markerdone;
icon = R.drawable.marker;
}
catch(Exception e) {
e.printStackTrace();
}
Marker marker1 = googleMap.addMarker(new MarkerOptions()
.position(new LatLng(49.793012, 9.926201))
.title(getString(R.string.Title1))
.snippet("")
.icon(BitmapDescriptorFactory.fromResource(icon)));
The problem is that you're calling getLastKnownLocation(), which will frequently return a null Location, since it doesn't explicitly request a new location lock.
So, when your app is crashing, it's due to a NullPointerException when trying to de-reference the Location object.
It's best to request location updates, and if you only need one, just un-register for location updates once the first onLocationChanged() callback comes in.
Here is an example using the FusedLocationProvider API, which automatically uses Network Location as well as GPS Location if needed:
Relevant imports for the Activity:
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
Activity:
public class MainActivity extends AppCompatActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
GoogleMap googleMap;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Marker marker;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buildGoogleApiClient();
mGoogleApiClient.connect();
}
#Override
protected void onResume() {
super.onResume();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
protected synchronized void buildGoogleApiClient() {
Toast.makeText(this,"buildGoogleApiClient", Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onMapReady(GoogleMap map) {
googleMap = map;
setUpMap();
}
public void setUpMap() {
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10);
mLocationRequest.setFastestInterval(10);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//mLocationRequest.setSmallestDisplacement(0.1F);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
//unregister location updates
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
//remove previously placed Marker
if (marker != null) {
marker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
//place marker where user just clicked
marker = googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("Current Location")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(5).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
build.gradle (change to whatever version of Google Play Services you are currently using):
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.1.1'
compile 'com.google.android.gms:play-services:7.5.0'
}
SupportMapFragment in the layout xml (you can use a MapFragment as well):
<fragment
android:id="#+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Using only Network Location:
The Map moves to the current location seconds after launch:

How do i add a marker on maps in android programming

So for some reason when i try adding a marker to a geopoint, the marker fails to show up at the given location. I tried researching what could be the problem but for some reason my code seems to follow everything that i researched on. Can someone guide me in the right direction?
import android.content.Context;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.text.DecimalFormat;
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
}
#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
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <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) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));
// Enable MyLocation Layer of Google Map
mMap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
// set map type
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get latitude of the current location
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
double longitude = location.getLongitude();
double latitude = location.getLatitude();
// Get longitude of the current location
// Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Show the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
//LatLng myCoordinates = new LatLng(latitude, longitude);
//CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(myCoordinates, 20);
//mMap.animateCamera(yourLocation);
mMap.animateCamera(CameraUpdateFactory.zoomTo(20));
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!").snippet("Consider yourself located"));
LatLng toLatLng = new LatLng(40.6937, 73.9859);
mMap.addMarker(new MarkerOptions().position( new LatLng(40.6937, 73.9859)).title("You location is here!").snippet("Consider it located"));
}
}
public void onFinish() {
// Your code here to do something after the Map is rendered
}
}
The main issue you mention:
the marker fails to show up at the given location
It looks like the main reason is that the getLastKnownLocation() is returning null, so it never gets into your code which sets the Marker at the current position.
Instead of calling that method, you can set up a location listener, which will explicitly request a new location.
I cleaned up your code a bit, and got it working. Note that I removed the use of getLastKnownLocation(), and moved the logic you had in there to the onLocationChanged() callback.
I also added functionality to remove the previous "current location" Marker, and add a new one every time the location changes.
Also note that the one Marker showing up at the equator near Africa was due to this line, so I just commented that out:
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));
Here is the full updated class code:
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.location.Criteria;
public class MapsActivity extends FragmentActivity implements LocationListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
LocationManager locationManager;
Marker marker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
#Override
protected void onPause() {
super.onPause();
//remove location listener
if (locationManager != null){
locationManager.removeUpdates(this);
}
}
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();
}
}
}
private void setUpMap() {
//This was the Marker at equator near Africa
//mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));
// Enable MyLocation Layer of Google Map
mMap.setMyLocationEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
}
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
}
}
public void onFinish() {
// Your code here to do something after the Map is rendered
}
#Override
public void onLocationChanged(Location location) {
double longitude = location.getLongitude();
double latitude = location.getLatitude();
// Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Show the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
if (marker != null) {
marker.remove();
}
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude))
.title("You are here!").snippet("Consider yourself located")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Result:
Edit:
You picked an interesting spot to put your hard-coded Marker.
I replaced the marker code with this:
LatLng toLatLng = new LatLng(40.6937, 73.9859);
// Create a LatLng object for the current location
LatLng latLng = new LatLng(40.6937, 73.9859);
// Show the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
if (marker != null) {
marker.remove();
}
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(40.6937, 73.9859))
.title("You are here!").snippet("Consider yourself located")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
And it placed the marker at the given location. Note that there is some strange effect going on due to different satellite images.
Initial result:
Zoomed out to see where we are!

drop a marker in one place even if i move around

I have an onclick_Park() method that only drops a marker in a specific position (which is at my home's position) even if I move into another place and click the Park button it will drop a marker at my home's position and not my current location.
Any help with be appreciated.
Here is myMainActivity.java class
package com.example.carfinder;
import java.util.ArrayList;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
public class MainActivity extends android.support.v4.app.FragmentActivity implements LocationListener {
GoogleMap googleMap;
LatLng myPosition ;
LatLng parkingPosition;
GMapV2Direction md;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// if Google Play Services are available then
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
googleMap.getUiSettings().setZoomControlsEnabled(false);
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
// 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
LatLng latLng = new LatLng(latitude, longitude);
myPosition = new LatLng(latitude, longitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(myPosition));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(16));
}
}
public void onClick_Clear(View v) {
// Removes all markers, overlays, and polylines from the map.
googleMap.clear();
}
public void onClick_Park(View v){
googleMap.addMarker(new MarkerOptions().position(myPosition).title("Parking Position"));
parkingPosition = myPosition;
}
public void onClick_getDirections(View v){
md = new GMapV2Direction();
googleMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
//org.w3c.dom.Document doc = md.getDocument(myPosition,parkingPosition,
// GMapV2Direction.MODE_DRIVING);
ArrayList<LatLng> directionPoint = md.getDirection(md.getDocument(myPosition,parkingPosition,
GMapV2Direction.MODE_DRIVING));
PolylineOptions rectLine = new PolylineOptions().width(3).color(
Color.RED);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
Polyline polylin = googleMap.addPolyline(rectLine);
}
public void onClick_Traffic(View v){
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
}
From your code, Location location = locationManager.getLastKnownLocation(provider); the location variable will fetch only the last known location stored by the app and not the present location.
Solution: Call the function to mark inside the
public void onLocationChanged(Location arg0) {}
so that it checks your location every time when it is changed.
UPDATE : Refer this link.
http://wptrafficanalyzer.in/blog/showing-current-location-using-onmylocationchangelistener-in-google-map-android-api-v2/

Google Maps Android Api V2 Driving Route Isn't Working

i don't have any idea why my code is not working... I made a ListArray that which keep my CurrentPosition continuosly and draw it with a polyline. here is my code.
MainActivity.java
package com.pondys.limon.touregsys;
import java.util.ArrayList;
import java.util.List;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.SyncStateContract.Constants;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
double latitude,longitude,firstLatitude,firstLongitude;
private ArrayList<LatLng> arrayPoints = null;
PolylineOptions polylineOptions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
// Getting latitude of the current location
firstLatitude = location.getLatitude();
// Getting longitude of the current location
firstLongitude = location.getLongitude();
CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng(latitude,longitude));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
googleMap.moveCamera(center);
googleMap.animateCamera(zoom);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onLocationChanged(Location location) {
// 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);
ArrayList<LatLng> list = new ArrayList<LatLng> ();
list.add(latLng);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
PolylineOptions o = new PolylineOptions ().width(3).color(0xFFEE8888);
for(int i = 0; i<list.size(); i++){
o.add(new LatLng(latitude,longitude));
}
googleMap.addPolyline(o);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
there is no any route showing when i execute it...
You have to do it like this :
Polyline pathOptions = googleMap.addPolyline(new PolylineOptions().add(new LatLng(source_latitude, source_longitude), new LatLng(destination_latitude, destination_longitude)));
// Set the polyline's color to blue
pathOptions.setColor(Color.BLUE);
// Set the polyline's width
pathOptions.setWidth(2);

Categories

Resources