0

I am trying to add current location mark to my android Google map application in Android Studio.

My code:

private void setUpMap() {
Location location = null;
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
Marker marker;
marker = mMap.addMarker(new MarkerOptions().position(new LatLng((location.getLatitude()), location.getLongitude())).title("Marker"));}

It causes my application to crash. Underneath there are mistakes that appeared while running my application:

http://postimg.org/image/qrxdo9dl5/full/

(I used postimage to upload a larger size screen-shot)


Before I modified my code, I had a working code set to position 0,0:

private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));

Then I tried to change location '0,0' to read current latitude and longitude and show it on my Google map. I changed my code based on this post: How to get the current location in Google Maps Android API v2?

I am a java beginner and any help is much appreciated. Thank you very much for any help.

Community
  • 1
  • 1
martyna
  • 13
  • 3
  • How do you plan on getting a valid `Location` Object? Currently you just declare `location` and set it to `null`, hence the `NullPointerException` – Daniel Nugent Apr 14 '15 at 21:12

1 Answers1

0

You are getting a NullPointerException because your Location object is set to null. In the linked answer the location object comes from the location callback.

public void onMyLocationChange(Location location) // location object here

You can easily get the Location from your map reference like so

Location location = mMap.getMyLocation();

However this method is deprecated and using the location API is encouraged. To get location from the API you can follow this guide:

https://developer.android.com/training/location/retrieve-current.html

You build a GoogleApiClient, connect it, and then use it to get a location.

Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Oguz Babaoglu
  • 299
  • 2
  • 7