I am trying to get current location in map fragment but the crashes with an error in line googleMap.setMyLocationEnabled(true);
I used Location and Latlang to detect current location.
mapFragment.java
public class mapFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
Location location;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.fragment_map, 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.setMyLocationEnabled(true);
googleMap = mMapView.getMap();
// latitude and longitude
LatLng lat = new LatLng(location.getLatitude(), location.getLongitude());
/*double latitude = 17.385044;
double longitude = 78.486671;*/
// create marker
MarkerOptions marker = new MarkerOptions().position(
lat).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(lat).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_map.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" />
Looks like you have a few issues, but the crash is happening because you need to call getMap() before you call setMyLocationEnabled().
Change this:
googleMap.setMyLocationEnabled(true);
googleMap = mMapView.getMap();
...to this:
googleMap = mMapView.getMap();
googleMap.setMyLocationEnabled(true);
Updated: I was able to get this code working.
Getting the current location should be done with the Fused Location Provider API, but that is beyond the scope of this question.
The method in this sample code might work on older devices, but on 4.4.4 it's returning a null location due to getMyLocation() being depricated.
However, with the null check in place the map displays correctly, and you can click on the location button to have the map move to your current location.
MapView mMapView;
private GoogleMap googleMap;
Location location;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.fragment_main, 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();
googleMap.setMyLocationEnabled(true);
location = googleMap.getMyLocation();
if (location != null) {
// latitude and longitude
LatLng lat = new LatLng(location.getLatitude(), location.getLongitude());
//double latitude = 17.385044;
//double longitude = 78.486671;
//LatLng lat = new LatLng(latitude,longitude);
// create marker
MarkerOptions marker = new MarkerOptions().position(
lat).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(lat).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
// Perform any camera updates here
return v;
}
You can use the setOnMyLocationChangeListener method to get the current location. Download the source here(Show Google Map In Android)
MainActivity.Java
package deepshikha.googlemap;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
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;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends AppCompatActivity {
public GoogleMap googleMap;
private static final int REQUEST_PERMISSIONS = 100;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.btn);
fn_permission();
fn_currentlocation ();
}
public void fn_currentlocation (){
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
try {
googleMap.setMyLocationEnabled(true);
} catch (Exception e) {
}
if (googleMap != null) {
googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
double current_latitude = arg0.getLatitude();
double currrent_longitude = arg0.getLongitude();
LatLng current_latLng = new LatLng(current_latitude, currrent_longitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(current_latLng));
Log.e("CURRENT LONGITUDE", currrent_longitude + "");
Log.e("CURRENT LATITUDE", current_latitude + "");
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
googleMap.addMarker(new MarkerOptions().position(current_latLng).title("Marker"));
}
});
}
}
}
private void fn_permission(){
if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) ||
(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) &&
(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_PERMISSIONS);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
} else {
Toast.makeText(MainActivity.this, "The app was not allowed to read or write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
}
}
Related
I get this error
NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setMyLocationEnabled(boolean) on a null object reference
and the app crashes due to this error.i want to mentioned that i searched on the internet and here for an answer but not found anything
Here is my code:
public class MapsActivity extends FragmentActivity
implements OnMapReadyCallback,
GoogleMap.OnMapClickListener,
GoogleMap.OnMapLongClickListener,
GoogleMap.OnMarkerClickListener {
private GoogleMap mMap;
private GoogleMap googleMap;
private ArrayList<LatLng> arrayPoints = null;
PolylineOptions polylineOptions;
private boolean checkClick = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
arrayPoints = new ArrayList<LatLng>();
// 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);
// display zoom map
googleMap.setOnMapClickListener(this);
googleMap.setOnMapLongClickListener(this);
googleMap.setOnMarkerClickListener(this);
}
public GoogleMap getmMap() {
return mMap;
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(final GoogleMap googleMap) {
mMap = googleMap;
googleMap.setMyLocationEnabled(true);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(final LatLng latLng) {
if (checkClick == false) {
LatLng currentLocation = null;
Marker marker = googleMap.addMarker(new MarkerOptions().position(currentLocation)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.point)));
}
}
});
}
#Override
public void onMapLongClick(LatLng latLng) {
googleMap.clear();
arrayPoints.clear();
checkClick = false;
}
#Override
public boolean onMarkerClick(Marker marker) {
// TODO Auto-generated method stub
System.out.println("Marker lat long=" + marker.getPosition());
System.out.println("First postion check" + arrayPoints.get(0));
System.out
.println("**********All arrayPoints***********" + arrayPoints);
if (arrayPoints.get(0).equals(marker.getPosition())) {
System.out.println("********First Point choose************");
countPolygonPoints();
}
return false;
}
private void countPolygonPoints() {
if (arrayPoints.size() >= 3) {
checkClick = true;
PolygonOptions polygonOptions = new PolygonOptions();
polygonOptions.addAll(arrayPoints);
polygonOptions.strokeColor(Color.BLUE);
polygonOptions.strokeWidth(7);
polygonOptions.fillColor(Color.CYAN);
Polygon polygon = googleMap.addPolygon(polygonOptions);
}
}
#Override
public void onMapClick(LatLng latLng) {
}
}
There are multiple issues in your code.
First of all, you are using two GoogleMap variables and not correctly initializing either. You only need one.
private GoogleMap mMap;
Secondly, in order to use setMyLocationEnabled you need to request location permissions from the user at runtime:
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
}
Then you are setting currentLocation to null and passing this null variable to your new marker. Instead, use the actual latLng:
mMap.addMarker(new MarkerOptions().position(latLng));
Finally, you are not actually adding any items to your arrayPoints ArrayList. I'd assume you want to do something like this:
arrayPoints.add(marker.getPosition());
Full working code below.
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
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;
import com.google.android.gms.maps.model.PolygonOptions;
import java.util.ArrayList;
public class MapsActivity extends FragmentActivity
implements OnMapReadyCallback,
GoogleMap.OnMapClickListener,
GoogleMap.OnMapLongClickListener,
GoogleMap.OnMarkerClickListener {
private GoogleMap mMap;
private ArrayList<LatLng> arrayPoints = null;
private boolean checkClick = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
arrayPoints = new ArrayList<>();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(final GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
}
mMap.setOnMapClickListener(this);
mMap.setOnMapLongClickListener(this);
mMap.setOnMarkerClickListener(this);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(final LatLng latLng) {
if (!checkClick) {
mMap.addMarker(new MarkerOptions().position(latLng));
}
}
});
}
#Override
public void onMapLongClick(LatLng latLng) {
mMap.clear();
arrayPoints.clear();
checkClick = false;
}
#Override
public boolean onMarkerClick(Marker marker) {
arrayPoints.add(marker.getPosition());
System.out.println("Marker lat long=" + marker.getPosition());
System.out.println("First position check" + arrayPoints.get(0));
System.out
.println("**********All arrayPoints***********" + arrayPoints);
if (arrayPoints.get(0).equals(marker.getPosition())) {
System.out.println("********First Point choose************");
countPolygonPoints();
}
return false;
}
private void countPolygonPoints() {
if (arrayPoints.size() >= 3) {
checkClick = true;
PolygonOptions polygonOptions = new PolygonOptions();
polygonOptions.addAll(arrayPoints);
polygonOptions.strokeColor(Color.BLUE);
polygonOptions.strokeWidth(7);
polygonOptions.fillColor(Color.CYAN);
mMap.addPolygon(polygonOptions);
}
}
#Override
public void onMapClick(LatLng latLng) {
}
}
Hope this helps!
Trying to fecth the current location in the fragment. While getting the permission, not abot to get the activity context. I am getting the activty context in other fragments, but do not know why it shows the error for
mMap.setMyLocationEnabled(true);
Please help
Goole Maps Fragment:
package com.example.mudasir.login.fragments;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.mudasir.login.R;
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.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class LocatorsFragment extends Fragment implements OnMapReadyCallback, View.OnClickListener {
private GoogleMap mMap;
private Button btnShowroom;
private Button btnService;
private Button btnParts;
private Button btnGas;
private Button btnAtm;
private Button btnSearch;
private EditText searchQuery;
Resources stringArrayResource;
private String[] showroomAddresses;
private String[] serviceAddresses;
private String[] partsAddresses;
private String searchQueryString;
private android.location.Address address = null;
List<Address> addressList = null;
LatLng latLng;
Geocoder geocoder;
Marker marker;
LatLngBounds bounds;
CameraUpdate cu;
ProgressDialog dialog;
boolean flag = false;
public LocatorsFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_maps_, container, false);
initUI(view);
return view;
}
private void initUI(View view) {
btnShowroom = (Button) view.findViewById(R.id.btn_showroom);
btnService = (Button) view.findViewById(R.id.btn_service);
btnParts = (Button) view.findViewById(R.id.btn_parts);
btnGas = (Button) view.findViewById(R.id.btn_gas);
btnAtm = (Button) view.findViewById(R.id.btn_atm);
btnSearch = (Button) view.findViewById(R.id.btn_search);
searchQuery = (EditText) view.findViewById(R.id.editext_search);
btnShowroom.setOnClickListener(this);
btnService.setOnClickListener(this);
btnParts.setOnClickListener(this);
btnGas.setOnClickListener(this);
btnAtm.setOnClickListener(this);
btnSearch.setOnClickListener(this);
stringArrayResource = getActivity().getResources();
showroomAddresses = stringArrayResource.getStringArray(R.array.showroom_array);
serviceAddresses = stringArrayResource.getStringArray(R.array.service_array);
partsAddresses = stringArrayResource.getStringArray(R.array.parts_array);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.maps);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(getActivity(), 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.
}
mMap.setMyLocationEnabled(true);
}
public void render_Map(String[] addresses,LatLngBounds.Builder builder)
{
//mMap.clear();
geocoder = new Geocoder(getActivity());
for (int i = 0; i < 5; i++) {
try {
addressList = geocoder.getFromLocationName(addresses[i], 1);
} catch (IOException e) {
e.printStackTrace();
}
address = addressList.get(0);
latLng = new LatLng(address.getLatitude(), address.getLongitude());
marker = mMap.addMarker(new MarkerOptions().position(latLng).title(addresses[i]));
builder.include(marker.getPosition());
}
bounds = builder.build();
int padding = 0;
cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
mMap.animateCamera(cu);
}
#Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.btn_showroom:
//new ShowProgressBar().execute("abc",null,null);
LatLngBounds.Builder builder1 = new LatLngBounds.Builder();
render_Map(showroomAddresses,builder1);
flag = true;
// dialog.cancel();
break;
case R.id.btn_service:
LatLngBounds.Builder builder2 = new LatLngBounds.Builder();
render_Map(serviceAddresses,builder2);
break;
case R.id.btn_parts:
LatLngBounds.Builder builder3 = new LatLngBounds.Builder();
render_Map(partsAddresses,builder3);
break;
case R.id.btn_gas:
Toast.makeText(getActivity(),getString(R.string.in_progress_text), Toast.LENGTH_SHORT).show();
break;
case R.id.btn_atm:
Toast.makeText(getActivity(),getString(R.string.in_progress_text), Toast.LENGTH_SHORT).show();
break;
case R.id.btn_search:
searchQueryString = searchQuery.getText().toString();
List<Address> addressList1 = null;
if(searchQueryString != null && !searchQueryString.equals(""))
{
geocoder = new Geocoder(getContext());
try {
addressList1 = geocoder.getFromLocationName(searchQueryString, 1);
} catch (IOException e) {
e.printStackTrace();
}
address = addressList1.get(0);
latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title(searchQueryString));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
else
Toast.makeText(getActivity(),getString(R.string.missing_search_query_error_message), Toast.LENGTH_SHORT).show();
break;
}
}
private class ShowProgressBar extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(getActivity(), "",
"Loading. Please wait...", true);
}
#Override
protected Void doInBackground(String... strings) {
while (!flag == true)
{
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
}
}
}
Error Message: Error:(110, 180) error: incompatible types:
LocatorsFragment cannot be converted to Context
You are giving this instead of getActivity(). Correct in onMapReady() like this :
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), 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.
}
mMap.setMyLocationEnabled(true);
}
The problem is that you are doing
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
on line 110 and you need to do
ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)
So I have searched the internet for lots of different solutions to get my android phone to show current location through the Google Maps API using play services. I believe I have the right set-up but something is just not right.
Please see below the .java and .xml code.
Java
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.os.Bundle;
import android.provider.SyncStateContract;
import android.support.v4.app.FragmentActivity;
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.UiSettings;
import com.google.android.gms.maps.model.CameraPosition;
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;
private UiSettings mUiSettings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
android.support.v4.app.FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment mySupportMapFragment
= (SupportMapFragment) myFragmentManager.findFragmentById(R.id.map);
}
private void centerMapOnMyLocation() {
mMap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(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);
Location location = mMap.getMyLocation();
// Getting latitude
double latitude = location.getLatitude();
// Getting longitude
double longitude = location.getLongitude();
LatLng latlng;
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(#NonNull String[] permissions, int requestCode)
// 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 Activity#requestPermissions for more details.
return;
}
Location myLocation = locationManager.getLastKnownLocation(provider);
if (location != null) {
//Create a LatLng object for the current location
latlng = new LatLng(latitude, longitude);
} else {
locationManager.requestLocationUpdates(provider, 20000, 0, (LocationListener) this);
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
tools:context="example.navigationapplication_10.MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
</LinearLayout>
Many thanks
Try using this class to get the Latitude and Longitude..
import android.app.AlertDialog.Builder;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
public class GPSTracker extends Service implements LocationListener {
private Context context;
boolean isGPSEnabled=false;
boolean isNetworkEnabled=false;
boolean canGetLocation=false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES=10;
private static final long MIN_TIME_BW_UPDATES=1000*60*1;
protected LocationManager locationManager;
public GPSTracker(Context context)
{
this.context=context;
getLocation();
}
public Location getLocation()
{
try{
locationManager=(LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled)
{
showSettingsAlert();
}
else{
this.canGetLocation=true;
if(isNetworkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager !=null)
{
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location !=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
if(isGPSEnabled){
if(location==null)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager !=null)
{
location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location !=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return location;
}
public void stopUsingGPS()
{
if(locationManager !=null)
{
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude()
{
if(location!=null)
{
latitude=location.getLatitude();
}
return latitude;
}
public double getLongitude()
{
if(location!=null)
{
longitude=location.getLongitude();
}
return longitude;
}
public boolean canGetLocation(){
return this.canGetLocation;
}
public void showSettingsAlert(){
Builder alertDialog=new Builder(context);
alertDialog.setTitle("GPS Settings");
alertDialog.setMessage("GPS is not enabled.Do you want to go to the settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
And for marking your position in the map
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
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;
GPSTracker gps;
#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;
try {
gps = new GPSTracker(MapsActivity.this);
if (gps.canGetLocation) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
LatLng sydney = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(sydney).title("I am here"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
for(int i=0;i<MainActivity.nameArray.length;i++)
{
latitude=Double.parseDouble(MainActivity.latArray[i]);
longitude=Double.parseDouble(MainActivity.lonArray[i]);
LatLng shops = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(shops).title(MainActivity.nameArray[i]));
}
} else {
gps.showSettingsAlert();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Hope this Helps
I am not able to show the compass icon and the my location icon either. I have the code googleMap.getUiSettings.setMyLocationButtonEnabled(true) and googleMap.getUiSettings().setCompassEnabled(true); but it is not showing on the maps.
package com.ctc.weathermap;
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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.Toast;
public class WeatherMapActivity extends Activity implements LocationListener {
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather_maps_main);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!enabledGPS) {
Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
else if(!enabledWiFi) {
Toast.makeText(this, "Network signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
initializeMap();
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
}
private void initializeMap() {
// check if map is created
if(googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap(); // creates the map
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Map could not be created", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
protected void onResume() {
super.onResume();
initializeMap();
}
#Override
public void onLocationChanged(Location location) {
googleMap.clear();
MarkerOptions marker = new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude()));
marker.title("Current location");
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
googleMap.addMarker(marker);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 16));
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
The rest of the code works such as markers and what not. I have tried putting the code for location and compass in initializeMap() but it still does not show up. I would appreciate any help. Thank you!
You havent enabled the my-location layer.Check this link for more details
So please do
googleMap.setMyLocationEnabled(true);
before
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
This will make your setMyLocationButton come up..
And,the compass icon will appear only if you rotate the map to not align to north.
Here is the case that i would like to add a Google API into an action bar which goes to a fragment. But, it failed because the fragment class has to extends FragmentActivity while the action bar not allowed it, anyone could help to fix it? Thanks very much!
MainHome.java
package com.example.demo3;
import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
public class MainHome extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainhome);
initView();
}
private void initView() {
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
actionBar.addTab(actionBar
.newTab()
.setText("My Information")
.setTabListener(
new MyTabListener<FragmentPage1>(this,
FragmentPage1.class)));
actionBar.addTab(actionBar
.newTab()
.setText("My Location")
.setTabListener(
new MyTabListener<FragmentPage2>(this,
FragmentPage2.class)));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.prelog, menu);
return true;
}
}
Fragment2.java
package com.example.demo3;
import android.app.Fragment;
import android.os.Bundle;
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.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 FragmentPage2 extends Fragment {
static final LatLng HAMBURG = new LatLng(53.558, 9.927);
static final LatLng KIEL = new LatLng(53.551, 9.993);
private GoogleMap map;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.locationhome, null, false);
map = ((SupportMapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
Marker hamburg = map.addMarker(new MarkerOptions().position(HAMBURG)
.title("Hamburg"));
Marker kiel = map.addMarker(new MarkerOptions()
.position(KIEL)
.title("Kiel")
.snippet("Kiel is cool")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
return v;
}
}
It brings that I need to extend FragmentActivity to enable
map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
. However, it will make
actionBar.addTab(actionBar
.newTab()
.setText("My Location")
.setTabListener(
new MyTabListener<FragmentPage2>(this,
FragmentPage2.class)));
failed. Anyone could have some suggestion?
Thanks very much!
use mapview instead of mapfragment like this
<com.google.android.gms.maps.MapView
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
and modify java file like this
public class MyMapFragment extends Fragment {
private MapView mMapView;
private GoogleMap mMap;
private Bundle mBundle;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.map_fragment, container, false);
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
// TODO handle this situation
}
mMapView = (MapView) inflatedView.findViewById(R.id.map);
mMapView.onCreate(mBundle);
setUpMapIfNeeded(inflatedView);
return inflatedView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = savedInstanceState;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.map)).getMap();
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
}