I am trying to add multiple markers on GoogleMap. This is what I am doing:
private void initilizeMap() {
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
if (googleMap != null)
addMarkers();
// Getting LocationManager object from System Service
// LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria,
true);
// Getting Current Location
Location location = locationManager
.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager
.requestLocationUpdates(provider, 20000, 0, this);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
Following function adds markers:
private void addMarkers() {
try {
for (String title : locations.keySet()) {
if (locations.get(title).getLatitude() != 0
&& locations.get(title).getLongitude() != 0) {
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(locations.get(title).getLatitude(),
locations.get(title).getLongitude()))
.title(title);
marker.icon(BitmapDescriptorFactory
.fromResource(R.drawable.pin_map));
// adding marker
googleMap.addMarker(marker);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
But markers are not displaying, though they are adding up on GoogleMap which I checked while debugging. No exception coming as well. I tried to change the icon image, still not working.
You are most probably using the old int values for latitude/longitude as they where expected for the GeoPoint of the previous GoogleMaps API. These are 1 million times too big for the new LatLng object, which expects double values rather than integers.
Related
i have a problem while loading map in lollipop version i cant get location while i search in map. it showing no location found, but it works in above marsmallow version.i dont know what mistake i have done.pls anyone give a solution to find out.
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(provider, 1000, 1, locationListener);
currentLocation = locationManager.getLastKnownLocation(provider);
//currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (currentLocation != null) {
current = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
//get location details
Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(current.latitude, current.longitude, 1);
Log.e(TAG, "addresses: "+addresses );
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
addr = addresses.get(0).getAddressLine(0);
}
CurrMarker = googleMap.addMarker(new MarkerOptions().position(current).title("Current Position").snippet(addr));
addCameraToMap(current);
} else {
Toast.makeText(this, "UnAvailable", Toast.LENGTH_SHORT).show();
}
Add following permission in AndroidManifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
First Add Permission to your Manifest file:
After Permission added to your Manifest:
int permissionPhoneState = ContextCompat.checkSelfPermission("Your Activity Name",
Manifest.permission.ACCESS_FINE_LOCATION);
int permissionPhoneState1 = ContextCompat.checkSelfPermission("Your Activity Name", Manifest.permission.ACCESS_COARSE_LOCATION);
if ((permissionPhoneState == PackageManager.PERMISSION_GRANTED) && (permissionPhoneState1 == PackageManager.PERMISSION_GRANTED)) {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
location(location);
} else {
ActivityCompat.requestPermissions("Your Activity Name", new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
}
private void location(Location location) {
if (location != null) {
location.setLatitude(location.getLatitude());
location.setLongitude(location.getLongitude());
final MarkerOptions markerOptions = new MarkerOptions();
final LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
markerOptions.position(latLng);
}
}
Hope this one help you
locationManager.requestLocationUpdates() is an Asynchronous call you are using currentLocation = locationManager.getLastKnownLocation(provider); which might not have received your current location yet as async call might not have been completed. Make sure you are using onLocationChanged() callback to get your location.
I am working on google map api v2. I have a button that adds marker to my current location.
Map can get my location right but sometimes (not every time) when i want to add marker to that location, marker goes far away from the blue dot.
I want to add my marker exactly on blue dot.
and this is my code for findMe button:
ImageButton findMyLocation_btn = (ImageButton) findViewById(R.id.findme);
if (findMyLocation_btn != null) {
findMyLocation_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
} else {
currentLocation = mMap.getMyLocation();
if ( marker1 == null && currentLocation != null) {
new onMyLocationClick().execute();
}
}
}
});
and onMyLocationClick()
private class onMyLocationClick extends AsyncTask{
#Override
protected Object doInBackground(Object[] params) {
Geocoder gc = new Geocoder(MainActivity.this);
List<Address> list = null;
try {
list = gc.getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
} catch (Exception ex) {
ex.printStackTrace();
}
if (list != null) {
add = list.get(0);
}
try {
origin = new LatLng(add.getLatitude(),add.getLongitude());
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute (Object o){
createMarker(add.getLatitude(), add.getLongitude(), add.getLocality(), add.getSubLocality());
}
}
Based on Google Maps doc:
This method was deprecated. use com.google.android.gms.location.FusedLocationProviderApi instead. FusedLocationProviderApi provides improved location finding and power usage and is used by the "My Location" blue dot.
The code to get current location is something like this:
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager
.getBestProvider(criteria, false));
double latitude = location.getLatitude();
double longitude = location.getLongitude();
For more advance solution you can use FusedLocationProvider as mentioned by google: https://developer.android.com/training/location/retrieve-current.html#GetLocation
how can I redirect my current Location when I open the Google Map
here is my code in SetUpMap()
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
mMap.setMyLocationEnabled(true);
And also how can I change the Marker ? I only get that blue circle in my location. I want to change it to a Pin
If you want to open map with your location through any activity then use this code
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=20.344,34.34&daddr=20.5666,45.345"));
startActivity(intent);
If you are using Google map then using location find lat long and pass this lat long in maps object
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
public void onLocationChanged(Location location) {
TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
Get the current location of the user as soon as your Map is ready and you need to animate the camera like this
Location location = this.mGoogleMap.getMyLocation();
if (location != null) {
LatLng target = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition position = this.mGoogleMap.getCameraPosition();
Builder builder = new CameraPosition.Builder();
builder.zoom(15);
builder.target(target);
this.mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(builder.build()));
}
So, getMyLocation() has to fetch the location of the user. Use can use PROVIDERS to fetch the location. You can also listen to location using LocationListener using GoogleApiClient. Kindly read the documentation of Getting the Last Known Location and Receiving Location Updates before posting here.
To give the custom marker for your location there is something called addMarker
mGoogleMap.addMarker(new MarkerOptions()
.position(new LatLng(location.getLatitude(), location.getLogitude()))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
You can try with this code, We can get our location in google map by NETWORK_PROVIDER. NETWORK_PROVIDER pick your location from your WIFI location or your network provider companies like(IDEA,AIRTEL,VODAPHONE) .
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
}
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(true);
LocationManager location_manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener listner = new getlatlngListner();
location_manager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 2000, 2000, listner);
location_manager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
} catch (Exception e) {
e.printStackTrace();
}
private MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.visible(true);
mMarkerOptions.icon(BitmapDescriptorFactory.fromBitmap(Your bitmap));
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng mPos = new LatLng(location.getLatitude(),location.getLongitude());
mMarkerOptions.position(mPos);
mMap.addMarker(mMarkerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(mPos));
mMap.animateCamera(CameraUpdateFactory.zoomTo(17));
}
});
google map v2 in android how to get current position and zoom in automatically and main countries selection point notification
setContentView(R.layout.activity_main);
try {
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
}
#SuppressLint("NewApi")
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
googleMap.animateCamera(CameraUpdateFactory.zoomTo(5.0f));
LocationManager mlocManager =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(0, 0))
.title("Your Location is"));
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
protected void onResume() {
super.onResume();
initilizeMap();
}
After analysing your question you could try this:
private LatLng getCurrentPosition(){
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria(); // set criteria for location provider:
criteria.setAccuracy(Criteria.ACCURACY_FINE); // fine accuracy
criteria.setCostAllowed(false); // no monetary cost
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
LatLng myPosition= new LatLng(location.getLatitude(), location.getLongitude());
Toast.makeText(this, "current position: "+ location.getLatitude() + "," + location.getLongitude(), Toast.LENGTH_SHORT).show();
return myPosition;
}
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))