How to add unlimited markers on click - google maps api - android

I'm developing an application using Google Maps API.
I'm trying to add a marker where the user press on the map and to draw a line between markers that the user have created.
I'v tried to add the method SetOnMapClickListener but every time I run my application in the virtual device it's immediately crushes.
I've also tried to locate the method in OnCreate method and in OnMapReady, but this is not working either.
I succeeded to add new markers but only by writing them...
On some tutorials that I've found I saw that they assign the google map object with mapFragment.getMap(), but I don't have this method.
Thanks!
Here is my code:
package com.example.user.testmap;
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.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity 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);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
double lit = latLng.latitude;
double lon = latLng.longitude;
mMap.addMarker(new MarkerOptions().position(new LatLng(lit, lon)));
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.addMarker(new MarkerOptions().position(new LatLng(20, 5)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(20, 5)));
}
}

try to remove your mMap.setOnMapClickListener in onCreate() then implements the GoogleMap.OnMapClickListener
like this.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapClickListener {
private GoogleMap mMap;
private ArrayList<Marker> arrMarkerList;
private ArrayList<Polyline> arrPolylineList;
#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);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapClickListener(this);
arrMarkerList = new ArrayList<>();
arrPolylineList = new ArrayList<>();
}
#Override
public void onMapClick(LatLng latLng) {
double lit = latLng.latitude;
double lon = latLng.longitude;
arrMarkerList.add(mMap.addMarker(new MarkerOptions().position(new LatLng(lit, lon))));
// Removing the existing polyline to draw a new.
for (Polyline polyline : arrPolylineList) {
polyline.remove();
}
if (arrMarkerList.size() > 1) {
PolylineOptions polylineOptions = new PolylineOptions();
for (Marker marker : arrMarkerList) {
polylineOptions.add(marker.getPosition());
}
arrPolylineList.add(mMap.addPolyline(polylineOptions));
}
}
}

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

Map application isn't updating location until Google maps location has been updated

I get the current location in my app only after the google maps is updated first, whereas if I don't update the Google maps, my app isn't able to get the current location.Here's my Java code:
MapsActivity.java
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
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.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
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 MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnMarkerDragListener,
GoogleMap.OnMapLongClickListener,
View.OnClickListener{
//Our Map
private GoogleMap mMap;
//To store longitude and latitude from map
private double longitude;
private double latitude;
//Buttons
private ImageButton buttonSave;
private ImageButton buttonCurrent;
private ImageButton buttonView;
//Google ApiClient
private GoogleApiClient googleApiClient;
#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);
//Initializing googleapi client
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
//Initializing views and adding onclick listeners
buttonSave = (ImageButton) findViewById(R.id.buttonSave);
buttonCurrent = (ImageButton) findViewById(R.id.buttonCurrent);
buttonView = (ImageButton) findViewById(R.id.buttonView);
buttonSave.setOnClickListener(this);
buttonCurrent.setOnClickListener(this);
buttonView.setOnClickListener(this);
}
#Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
//Getting current location
private void getCurrentLocation() {
mMap.clear();
//Creating a location object
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
//Getting longitude and latitude
longitude = location.getLongitude();
latitude = location.getLatitude();
//moving the map to location
moveMap();
}
}
//Function to move the map
private void moveMap() {
//String to display current latitude and longitude
String msg = latitude + ", "+longitude;
//Creating a LatLng Object to store Coordinates
LatLng latLng = new LatLng(latitude, longitude);
//Adding marker to map
mMap.addMarker(new MarkerOptions()
.position(latLng) //setting position
.draggable(true) //Making the marker draggable
.title("Current Location")); //Adding a title
//Moving the camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Animating the camera
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
//Displaying current coordinates in toast
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng latLng = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.setOnMarkerDragListener(this);
mMap.setOnMapLongClickListener(this);
}
#Override
public void onConnected(Bundle bundle) {
getCurrentLocation();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onMapLongClick(LatLng latLng) {
//Clearing all the markers
mMap.clear();
//Adding a new marker to the current pressed position
mMap.addMarker(new MarkerOptions()
.position(latLng)
.draggable(true));
}
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
//Getting the coordinates
latitude = marker.getPosition().latitude;
longitude = marker.getPosition().longitude;
//Moving the map
moveMap();
}
#Override
public void onClick(View v) {
if(v == buttonCurrent){
getCurrentLocation();
moveMap();
}}}
Here Is My Manifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.takecare">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Here Is My App Gradle dependencies
compile 'com.android.support:appcompat-v7:24.1.1'
compile 'com.android.support:design:24.1.1'
compile 'com.android.support:support-v4:24.1.1'
compile 'com.google.android.gms:play-services:9.4.0'
compile 'com.google.android.gms:play-services-location:9.4.0'
thy these lines of code you write wrong
this code for get current lat and long data
longitude = location.getLongitude();
latitude = location.getLatitude();
and you set this data to set on map
mMap = googleMap;
LatLng latLng = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.setOnMarkerDragListener(this);
mMap.setOnMapLongClickListener(this);
after update your location you are going to set this location
mMap.addMarker(new MarkerOptions()
.position(latLng)
.draggable(true));
where as your data is on latLng -34, 151
thats by you are not getting updated data on map just get latest data by using these lines of code
LatLng latLng = new LatLng(location.getLongitude(),location.getLatitude());
I have not checked your gradle or manifest please check at your end.
may be this code will help you );

how to use googlemap in fragment android? [duplicate]

This question already has answers here:
Using Google Maps inside a Fragment in Android
(2 answers)
Closed 7 years ago.
I find a tutorial accroding getmap() in stackoverflow but it was for old version.
this is new offical google tutorial for create map:
public class mapmain extends FragmentActivity implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.primary_layout);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
// Add a marker in Sydney, Australia, and move the camera.
LatLng sydney = new LatLng(-34, 151);
map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
how can I convert it to fragment class? (extend by fragment not FragmentActivity)
How to put Google Maps V2 on a Fragment
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
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.MarkerOptions;
/**
* A fragment that launches other parts of the demo application.
*/
public class MapFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.fragment_location_info, container,
false);
mMapView = (MapView) v.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();// needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
googleMap = mMapView.getMap();
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Perform any camera updates here
return v;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
fragment_location_info.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />

Android Google Maps Linkify Phone Number in Snippet

I am trying to linkify a phone number within a snippet of a google map. Given this code:
import com.google.android.gms.maps.*;
import com.google.android.gms.maps.model.*;
import android.app.Activity;
import android.os.Bundle;
public class MapPane extends Activity implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_activity);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
LatLng sydney = new LatLng(-33.867, 151.206);
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));
map.addMarker(new MarkerOptions()
.title("Sydney")
.snippet("1-800-555-5555")
.position(sydney));
}
}
How could I make thie snippet:
.snippet("1-800-555-5555")
Linkified, so if they click the marker, then click the phone number in the resulting snippet popup, Android will call that number?

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:

Categories

Resources