I tried to fetch a google map with current location but I got this error
FATAL EXCEPTION: main java.lang.NullPointerException
in
map= ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
java code
public class MapFragment extends Fragment{
private TextView locationText;
private TextView addressText;
private GoogleMap map;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.fragment_map, container, false);
locationText = (TextView) rootview.findViewById(R.id.location);
addressText = (TextView) rootview.findViewById(R.id.address);
//replace GOOGLE MAP fragment in this Activity
return rootview;
}
public void onMapReady(GoogleMap map) {
//make the call here. it will be called once the map is ready
replaceMapFragment();
}
private void replaceMapFragment() {
map= ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// Enable Zoom
map.getUiSettings().setZoomGesturesEnabled(true);
//set Map TYPE
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//enable Current location Button
map.setMyLocationEnabled(true);
//set "listener" for changing my location
map.setOnMyLocationChangeListener(myLocationChangeListener());
}
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener() {
return new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Marker marker;
marker = map.addMarker(new MarkerOptions().position(loc));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
locationText.setText("You are at [" + longitude + " ; " + latitude + " ]");
//get current address by invoke an AsyncTask object
//new GetAddressTask(getActivity()).execute(String.valueOf(latitude), String.valueOf(longitude));
}
};
}
}
This may happened because the map is not ready at the moment.
#Override
public void onMapReady(GoogleMap googleMap) {
//make the call here. it will be called once the map is ready
replaceMapFragment();
}
In response to your comment on Kasun's answer, to display the current location marker on the map, call:
googleMap.setMyLocationEnabled(true);
Edit
import com.google.android.gms.maps.SupportMapFragment;
public class MapFragment extends SupportMapFragment
implements OnMapReadyCallback {
#Override
public void onCreate(Bundle inState) {
super.onCreate(inState);
// start a task for connecting to the map
// onMapReady() will be called when it is complete
getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap
// Enable Zoom
map.getUiSettings().setZoomGesturesEnabled(true);
//set Map TYPE
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//enable Current location Button
map.setMyLocationEnabled(true);
//set "listener" for changing my location
map.setOnMyLocationChangeListener(myLocationChangeListener());
}
}
Related
This question already has answers here:
Get Latitude and longitude of marker in google maps
(2 answers)
Closed 5 years ago.
How to get latitude and longitude from pin that user dropped ? Like Google map, we click a pin on the map , it shows the latitude and longitude about the pin. Could anyone help me ? Thanks a lot.
Like the picture ,it shows latitude and longitude .
Images
public class YOURACTIVITY extends AppCompatActivity implements OnMapReadyCallback
private GoogleMap mMap;
<--
OnCreate
SupportMapFragment map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
map.getMapAsync(this);
-->
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
double mLat = LATITUDE;
double mLon = LONTITUDE;
LatLng mylocation = new LatLng(mLat, mLon);
mMap.addMarker(new MarkerOptions().position(mylocation).snippet("TEXT BELLOW TITLE").title("TITLE")).showInfoWindow();
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mylocation,15));
}
UPDATE
Try to do add something like this. Create custom layout and add information
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View view = MainActivity.getLayoutInflater().inflate(R.layout.map_custom, null);
TextView titleTextView = (TextView) view.findViewById(R.id.map_title);
TextView snippetTextView = (TextView) view.findViewById(R.id.map_snippet);
titleTextView.setText(marker.getTitle());
snippetTextView.setText(marker.getSnippet());
return view;
}
});
Try this efficient solution:
public void onMapLongClick(LatLng point) {
pin.setText("New marker added#" + point.toString());
//Create a marker object
Marker myMarker = map.addMarker(new MarkerOptions().position(point).title(point.toString()));
//And now you can use it's values
myMarker.getPosition().latitude;
myMarker.getPosition().longitude;
}
You can use the setOnMarkerDragListener method:
mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
double latitude = marker.getPosition().latitude;
double longitude = marker.getPosition().longitude;
}
});
The short of it is to use the Marker.getPosition() method, maybe in a toast:
#Override
public void onMarkerDragEnd(Marker marker) {
LatLng pos = marker.getPosition();
Toast.makeText(MainActivity.this, "Point coordinates: " + pos.latitude
+ ", " + pos.longitude, Toast.LENGTH_LONG).show();
}
Here is my code:
public class MapViewFragment extends Fragment implements OnMapReadyCallback {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.maps, container, false);
Context context =this.getContext();
GPSService mGPSService = new GPSService(context);
mGPSService.getLocation();
if (mGPSService.isLocationAvailable == false) {
} else {
// Getting location co-ordinates
lat1 = mGPSService.getLatitude();
lng1 = mGPSService.getLongitude();
}
mMapView.onCreate(savedInstanceState);
ActivityCompat.requestPermissions(getActivity(),new String[]{
android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
call.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
call();
}
});
mMapView.getMapAsync(this); //this is important
}
});*/
}
return v;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
m1 = googleMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1,lng1))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.anchor(0.5f, 0.5f)
.title("Title1")
.snippet("Snippet1"));
#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 onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mMapView.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
In program i getting current location lat and lang.When i moved to other location marker does not change. whenever I move the location has to change.
Current location value iam getting whenever i move location value does not change.want implement any method change the location.
i assume you've already created a marker to indicate your current position. like this
Marker currentLocation;
Now You need to implement LocationListener and update your MapView in the onLocationChanged callback
#Override
public void onLocationChanged(Location location) {
if(currentLocation != null){
currentLocation.remove();
}
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// 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);
currentLocation = googleMap.addMarker(new MarkerOptions().position(latLng)));
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
I used a Fragment implements LocationListener and i tried to get my current location , but i can't get it successfully. Do i miss something ?
public class TrafficInformation extends Fragment implements LocationListener{
private MapView mapView;
private GoogleMap googleMap;
private double myLatitude,myLongitude;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.traffic_information_fragment, container, false);
mapView = (MapView) view.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.onResume();
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
//part of android 6.0 permission
int flag = ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION);
if (flag != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
} else {
googleMap.setMyLocationEnabled(true);
}
// For dropping a marker at a point on the Map
//i set my current location over here-------------------
LatLng sydney = new LatLng(myLatitude, myLongitude);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
//For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(16).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
return view;
}
i try to get it from this function:
#Override
public void onLocationChanged(Location location) {
myLatitude=location.getLatitude();
myLongitude=location.getLongitude();
}
i can't get myLatitude and myLongitude location , why?
any help would be grateful.
You are not calling
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this)
You are only calling
googleMap.setMyLocationEnabled(true);
This don't request for location updates... just set a pin on your position on the map.
Check here to see how to request current location:
https://developer.android.com/training/location/receive-location-updates.html
First, I plot a Marker like this:
public void addMarker(String title,String lat,String Lng,int id,String address,int f)
{
marker= mMap.addMarker(new MarkerOptions().snippet(title)
.title(title+", "+address)
.position(new LatLng(Double.valueOf(lat), Double.valueOf(Lng)))
.icon(BitmapDescriptorFactory.fromResource(id)));
LatLng coordinate = new LatLng(Double.valueOf(lat), Double.valueOf(Lng));
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 10);
mMap.animateCamera(yourLocation);
mMarkerArray.add(marker);
}
After that I am trying to replace the Marker with another icon when ever I reached at any existing Location
#Override
public void onLocationChanged(Location location)
{
Log.d("latitude_main", "onlocation???");
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Log.e("latitude_main", "latitude--" + latitude+"longitude="+longitude);
current_lat= String.valueOf(latitude);
current_lng= String.valueOf(longitude);
Log.e("latitude_main","size-=="+salesmanlocationArrayList.size() );
for(int i=0;i<salesmanlocationArrayList.size();i++)
{
if(salesmanlocation.getLati().equals("12.9165757") && salesmanlocation.getLongi().equals("77.6101163"))
{
mMap.addMarker(new MarkerOptions()
.snippet(""+i).title(salesmanlocation.getFirm_name()+", "+salesmanlocation.getAddress())
.position(new LatLng(Double.valueOf(salesmanlocation.getLati().toString()), Double.valueOf(salesmanlocation.getLongi().toString())))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.event_events_select)));
}
mapFragment.getMapAsync(this);
}
}
I want to remove the marker from the map when the user visits that location.
You can simply define one OnMyLocationChangeListener class that performs your tasks, and set it on your GoogleMap instance, this way you can use it whenever you want in your application.
Step 1 - define your listener
public class MyMarkerLocationListener implements GoogleMap.OnMyLocationChangeListener {
List<Marker> markerList;
int MY_DISTANCE;
GoogleMap mMap;
public MyMarkerLocationListener(List<Marker> markerList, int meters, GoogleMap mMap)
{
this.markerList = markerList;
this.MY_DISTANCE = meters;
this.mMap = mMap;
}
#Override
public void onMyLocationChange(Location location) {
// your code/logic
//...
Location myNewLocation = location;
Location someMarkerLocation = new Location("some location");
//for each marker on your list
//check if you are close to it
for (Marker m : markerList) {
LatLng markerPosition = m.getPosition();
someMarkerLocation.setLatitude(markerPosition.latitude);
someMarkerLocation.setLongitude(markerPosition.longitude);
if (myNewLocation.distanceTo(someMarkerLocation) < MY_DISTANCE) {
//remove marker
m.remove();
//or if you still want to use it later
//m.setVisible(false);
// add your new marker
//mMap.addMarker(new MarkerOptions().icon()....);
}
}
}
}
After defining your class you just set the listener on your map on your fragment or activity code =)
Step 2 - instanciate the listener and set it
MyMarkerLocationListener myListener = new MyMarkerLocationListener(mMarkerArray, 100, mMap);
mMap.setOnMyLocationChangeListener(myListener);
UPDATE to answer your question in the comments:
You should initialize mMap before using it, take a look at this piece of code from this Stackoverflow question
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) {
//DO WHATEVER YOU WANT WITH GOOGLEMAP
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
map.setMyLocationEnabled(true);
map.setTrafficEnabled(true);
map.setIndoorEnabled(true);
map.setBuildingsEnabled(true);
map.getUiSettings().setZoomControlsEnabled(true);
}
}
don't forget your activity should implement the OnMapReadyCallback interface so the onMapReady method is called
you can use the map only after it is ready
Hope this helps!
I'm trying to post a marker onto a map from a separate fragment. So when you tap a button, the fragment manager will take you to the map fragment and then show you your newly placed marker. But I'm having some (nullPointer) issues.
I'm getting a null pointer because I'm trying to add a marker before the map loads. I've tried some methods to find a way to add the marker when the map is ready but I couldn't get anything to work.
Is there a clean solution to adding a marker when the map is ready?
Also, here's the error that comes up:
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
EDIT: The way I'm getting the marker information (LatLng) is with a method I found on stackoverflow. What it does is, it takes the address from an EditText and retrieves the Latitude and Longitude points from it. I use that to store it into 'marker' and 'point'. The method is found below...
UPDATE: It no longer gives me a null exception. The MapFragment loads but there's no marker to be seen.
In my PostFragment class:
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setUpSpinners();
Button button = (Button) getActivity().findViewById(R.id.postButton);
button.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
EditText editEvent = (EditText) getActivity().findViewById(R.id.map_location);
point = getLocationFromAddress(getActivity()
.getApplicationContext(), editEvent.getText().toString());
marker = new MarkerOptions().position(
new LatLng(point.latitude, point.longitude)).title("New Marker");
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frag, new GoogleMapFragment()).commit();
}
}
);
}
public void addThisMarker(GoogleMap googleMap) {
googleMap.addMarker(marker
.position(point)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
}
And in my MapFragment class:
#Override
public void onMapReady(GoogleMap googleMap) {
globalMap = googleMap;
setUpMap(); //just enabling some map properties here
PostFragment x = new PostFragment();
x.addThisMarker(globalMap);
}
**And this is the method I'm using, in PostFragment, to retrieve LatLng from an address
public LatLng getLocationFromAddress(Context context, String strAddress) {
Geocoder coder = new Geocoder(context);
List<Address> address;
LatLng p1 = null;
try {
address = coder.getFromLocationName(strAddress, 5);
if (address == null) {
return null;
}
Address location = address.get(0);
location.getLatitude();
location.getLongitude();
p1 = new LatLng(location.getLatitude(), location.getLongitude());
} catch (Exception ex) {
ex.printStackTrace();
}
return p1;
}
You can do it like this:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
MapFragment fMap = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
fmap.getMapAsync(this);
}
#Override
public void onMapReady(final GoogleMap googleMap) {
map = googleMap;
// Draw your marker here
}
}