public class location_a extends Fragment {
TextView location;
MapView mMapView;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.location_a, container, false);
location = (TextView) rootView.findViewById(R.id.add);
location.setText("Plot -315\nNext to Taj Hotel\nNear layout\nBangalore - 5600092\nKarnataka");
setUpMapIfNeeded();
return rootView;
}
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.
SupportMapFragment mMap = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map_fragment));
//Toast.makeText(getActivity(), "come in" + mMap, Toast.LENGTH_SHORT).show();
//mMap = fm.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
Toast.makeText(getActivity(), "come in", Toast.LENGTH_SHORT).show();
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(12.9120074,77.64910951)).title("Winfo Global"));
mMap.addMarker(new MarkerOptions().position(new LatLng(13.0120074,77.94910951)).title("xyz builder"));
// Enable MyLocation Layer of Google Map
mMap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getActivity().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);
Location myLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (myLocation!=null) {
double longitude = myLocation.getLongitude();
double latitude = myLocation.getLatitude();
String locLat = String.valueOf(latitude) + "," + String.valueOf(longitude);
// set map type
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get latitude of the current location
/// double latitude = myLocation.getLatitude();
// Get longitude of the current location
///double longitude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
LatLng myCoordinates = new LatLng(latitude, longitude);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(myCoordinates, 12);
mMap.animateCamera(yourLocation);
// Show the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(myCoordinates) // Sets the center of the map to LatLng (refer to previous snippet)
.zoom(17) // Sets the zoom
.bearing(90) // 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
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
// Zoom in the Google Map
mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
// mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!").snippet("Consider yourself located"));
}
}
HERE mMap shows always NULL so it not enter into if statment
if (mMap != null) {Toast.makeText(getActivity(), "comein", Toast.LENGTH_SHORT).show();
setUpMap();
}
pls help me to solve problem
It always null if Google Play services APK is not available in application, please can you check with your code
Try following code
SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
GoogleMap mMap = mapFrag.getMap();
Check here for full source code and sample
Edit
Make sure you have written following code in your layout to get map fragment from id.
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17);
Related
to start with, I am completely confused with various api's available for location and map. So, I even dont know if the code is optimal for sdk 27.(I have minimum sdk 24 set.)
The problem is this piece of code shows the current location well and fine, butand the map gets updated when the location is changed. But, that is not reflected in location. See, the polyline drawn from LatLong does not follow the current location.
Also, I am trying to implement FusedLocationProviderClient but thats probably not the case here.
Any help will be very welcome.
public class SecondFragment extends Fragment implements OnMapReadyCallback {
//Color stroke = new Color(222.0,135.0, 135.0,174.0);
private GoogleMap mMap;
public static SecondFragment newInstance() {
SecondFragment fragment = new SecondFragment();
return fragment;
}
public GoogleMap getMap() {
return mMap;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_second, null, false);
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return view;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
double latitude;
double longitude;
LocationManager locationManager = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]
{android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
} else {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
latitude = 0.0;
longitude = 0.0;
} else {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
latlang.Lat = latitude;
latlang.Lang = longitude;
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(latitude, longitude)).zoom(18).build();
double angle = Math.toRadians(93.833);
Point cPoint = mMap.getProjection().toScreenLocation(new LatLng(latitude,longitude));
System.out.println("mPoint X"+ cPoint.x);
System.out.println("mPoint Y"+ cPoint.y);
Point mPoint = new Point();
//Azimuth Pos only
double lat_azi = 2*Math.sin(angle)+cPoint.y;
double long_azi = 2*Math.cos(angle)+cPoint.x;
LatLng nat_azi =mMap.getProjection().fromScreenLocation(mPoint);
//private List<Point> mPoint = new ArrayList<Point>();
Marker marker = mMap.addMarker(new MarkerOptions()
.position(nat_azi)
.anchor(0.5f,0.5f)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.sun_pos_icon))
);
Marker marker_loc = mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.anchor(0.5f, 0.5f)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.location_icon))
);
mMap.addPolyline(new PolylineOptions()
.add(new LatLng(lat_azi, long_azi), new LatLng(latitude, longitude), new LatLng(0,0))
.width(15)
.color(Color.MAGENTA));
PathOfSun.getTime();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mMap.setMyLocationEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.getUiSettings().setZoomControlsEnabled(true); // true to enable
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
}
}
}
You can follow below link for Updating Marker position on the Map.
Move marker with gps in google map android
I am trying to fetch user's current location on Genymotion emulator.I already set the custom GPS longitute and latitute on Genymotion. Whenever i trying to open Google Maps the Current location can't show in it.
Here is my Code snippet.
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map1)).getMap();
googleMap.setMyLocationEnabled(true);
LocationManager locManager = (LocationManager) context
.getSystemService(context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String locProvider = locManager.getBestProvider(criteria, false);
Location location = locManager.getLastKnownLocation(locProvider);
Location myLocation = googleMap.getMyLocation();
if (myLocation != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("rajkot")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
} else {
Toast.makeText(context, "unable to find location", 20).show();
}
This is my screenshot.
Please help me i can't find the user's current location
I also Check it on real device It's not working
Try This.
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latestlatLng = new LatLng(latitude, longitude);
Marker myself = mMap.addMarker(new MarkerOptions().position(latestlatLng).title("It's Me!"));
// myself.setDraggable(true);
mMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude())));
}
});
may be you could change the getMyLocaton() method with a fusedLocationProviderClient objects getLastLocation() method.
i am developing application using google maps i am successfully get current location but i am unable to directly go to my location .i want to go to my current location when open my app and add some circle from that location please tell me how it is
my code
public class MainActivity extends FragmentActivity {
GoogleMap _googleMap;
LatLng myPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_googleMap = ((SupportMapFragment)
getSupportFragmentManager().findFragmentById(
R.id.map)).getMap();
if(_googleMap==null){
Toast.makeText(getApplicationContext(), "Google Map Not Available",
Toast.LENGTH_LONG).show();
}
LocationManager locationManger =
(LocationManager)getSystemService(LOCATION_SERVICE);
Criteria criteria=new Criteria();
String provider = locationManger.getBestProvider(criteria, true);
Location location = locationManger.getLastKnownLocation(provider);
if(location!=null){
double latitude = location.getLatitude();
double langitude = location.getLongitude();
LatLng latlang = new LatLng(latitude, langitude);
LatLngBounds curScreen =
_googleMap.getProjection().getVisibleRegion().latLngBounds;
curScreen.contains(latlang);
myPosition = new LatLng(latitude, langitude);
_googleMap.addMarker(new
MarkerOptions().position(myPosition).title("start"));
}
}
Possible duplicate of Google Maps v2 - set both my location and zoom in
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_g_maps);
GoogleMap googleMap;
LatLng myPosition;
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap = fm.getMap();
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
myPosition = new LatLng(latitude, longitude);
}
}
}
I've tried adding:
CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng(latitude,
longitude));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
googleMap.moveCamera(center);
googleMap.animateCamera(zoom);
or
googleMap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude) ,4) );
but Google Maps doesn't automatically zoom in once I've hit the button which calls this method. I still get the Google UI which I can click to zoom in on my Location, but I want it to automatically zoom in.
Any help please?
Try this is simple solution for your question
LatLng coordinate = new LatLng(lat, lng);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 5);
map.animateCamera(yourLocation);
and also..
It's possible to change location, zoom, bearing and tilt in one go. It is also possible to set the duration on the animatecamera call.
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(MOUNTAIN_VIEW) // Sets the center of the map to Mountain View
.zoom(17) // Sets the zoom
.bearing(90) // 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.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
Have a look at the docs here:
https://developers.google.com/maps/documentation/android/views?hl=fr-FR#moving_the_camera
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
Location locationCt;
LocationManager locationManagerCt = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationCt = locationManagerCt
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LatLng latLng = new LatLng(locationCt.getLatitude(),
locationCt.getLongitude());
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.addMarker(new MarkerOptions().position(latLng)
.title("My Spot").snippet("This is my spot!")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_car)));
googleMap.setMyLocationEnabled(true);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
In your XML file
<Button
android:id="#+id/Bzoomin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onZoom"
android:text="^" />
<Button
android:id="#+id/Bzoomout"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:onClick="onZoom"
android:text="v" />'
In your Java file
public void onZoom(View view)
{
if(view.getId() == R.id.Bzoomin)
{
mMap.animateCamera(CameraUpdateFactory.zoomIn());
}
if(view.getId() == R.id.Bzoomout)
{
mMap.animateCamera(CameraUpdateFactory.zoomOut());
}
}
For Kotlin
val location = CameraUpdateFactory.newLatLngZoom(latlng, 15F)
mMap.animateCamera(location)
I'm trying to mess around with the Maps API V2 to get more familiar with it, and I'm trying to start the map centered at the user's current location. Using the map.setMyLocationEnabled(true); statement, I am able to show my current location on the map. This also adds the button to the UI that centers the map on my current location.
I want to simulate that button press in my code. I am familiar with the LocationManager and LocationListener classes and realize that using those is a viable alternative, but the functionality to center and zoom in on the user's location seems to already be built in through the button.
If the API has a method to show the user's current location, there surely must be an easier way to center on the location than to use the LocationManager/LocationListener classes, right?
Try this coding:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));
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
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
After you instansiated the map object (from the fragment) add this -
private void centerMapOnMyLocation() {
map.setMyLocationEnabled(true);
location = map.getMyLocation();
if (location != null) {
myLocation = new LatLng(location.getLatitude(),
location.getLongitude());
}
map.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation,
Constants.MAP_ZOOM));
}
if you need any guidance just ask but it should be self explantory - just instansiate the myLocation object for a default one...
youmap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentlocation, 16));
16 is the zoom level
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
CameraUpdate center=CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(11);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
}
});
try this code :
private GoogleMap mMap;
LocationManager locationManager;
private static final String TAG = "";
#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(map);
mapFragment.getMapAsync(this);
arrayPoints = new ArrayList<LatLng>();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
LatLng myPosition;
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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.
return;
}
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
myPosition = new LatLng(latitude, longitude);
LatLng coordinate = new LatLng(latitude, longitude);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 19);
mMap.animateCamera(yourLocation);
}
}
}
Dont forget to add permissions on AndroidManifest.xml.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Here's how to do it inside ViewModel and FusedLocationProviderClient, code in Kotlin
locationClient.lastLocation.addOnSuccessListener { location: Location? ->
location?.let {
val position = CameraPosition.Builder()
.target(LatLng(it.latitude, it.longitude))
.zoom(15.0f)
.build()
map.animateCamera(CameraUpdateFactory.newCameraPosition(position))
}
}
private void setUpMapIfNeeded(){
if (mMap == null){
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();//invoke of map fragment by id from main xml file
if (mMap != null) {
mMap.setMyLocationEnabled(true);//Makes the users current location visible by displaying a blue dot.
LocationManager lm=(LocationManager)getSystemService(LOCATION_SERVICE);//use of location services by firstly defining location manager.
String provider=lm.getBestProvider(new Criteria(), true);
if(provider==null){
onProviderDisabled(provider);
}
Location loc=lm.getLastKnownLocation(provider);
if (loc!=null){
onLocationChanged(loc);
}
}
}
}
// Initialize map options. For example:
// mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
#Override
public void onLocationChanged(Location location) {
LatLng latlng=new LatLng(location.getLatitude(),location.getLongitude());// This methods gets the users current longitude and latitude.
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));//Moves the camera to users current longitude and latitude
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng,(float) 14.6));//Animates camera and zooms to preferred state on the user's current location.
}
// TODO Auto-generated method stub
check this out:
fun requestMyGpsLocation(context: Context, callback: (location: Location) -> Unit) {
val request = LocationRequest()
// request.interval = 10000
// request.fastestInterval = 5000
request.numUpdates = 1
request.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
val client = LocationServices.getFusedLocationProviderClient(context)
val permission = ContextCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_FINE_LOCATION )
if (permission == PackageManager.PERMISSION_GRANTED) {
client.requestLocationUpdates(request, object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
val location = locationResult?.lastLocation
if (location != null)
callback.invoke(location)
}
}, null)
}
}
and
fun zoomOnMe() {
requestMyGpsLocation(this) { location ->
mMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(
LatLng(location.latitude,location.longitude ), 13F ))
}
}
This is working Current Location with zoom for Google Map V2
double lat= location.getLatitude();
double lng = location.getLongitude();
LatLng ll = new LatLng(lat, lng);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, 20));
In kotlin, you will get the current location then move the camera like this
map.isMyLocationEnabled = true
fusedLocationClient.lastLocation
.addOnSuccessListener { location: Location? ->
if (location != null) {
map.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(location.latitude, location.longitude), 14f))
}
}
Also you can animate the move by using this function instead
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.latitude, location.longitude), 14f))