Please help me, how can I set a marker in current location?
Below my code onCreate, addMarker and createMapView.
onCreate
public class MapActivity extends Activity {
GoogleMap googleMap;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_activity);
createMapView();
addMarker();
}
addMarker
private void addMarker() {
if (null != googleMap) {
googleMap.addMarker(new MarkerOptions()
.title("Marker")
.position(new LatLng(0, 0))
.draggable(true));
}
}
createMapView
private void createMapView() {
try {
if (null == googleMap) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.mapView)).getMap();
if (null == googleMap) {
Toast.makeText(getApplicationContext(), "Error creating map", Toast.LENGTH_LONG).show();
}
}
} catch (NullPointerException e) {
Log.e("mapApp", e.toString());
}
}
You are setting your marker at (0, 0)
.position(new LatLng(0, 0))
You can get the latest position in onLocationChanged.
Get the latitude and longitude:
new LatLng(location.getLatitude(), location.getLongitude())
Use the LatLng object to set your marker.
Get the latitude and longitude location from FusedLocationApi as GoogleApiClient.FusedLocationApi.getLastLocation() and then call addMarker using these lat/longs.
Hope this helps.
First of all you need to get current latlng of your position
and create latlng object based on it , and when you get latlng successfully
use this method
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
fromPosition = new LatLng(latti, longi);
googleMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.orangedoticon)).title("helo0o0"));
You must get your lat and lng of your current location and put this code.
#Override
public void onMapReady(GoogleMap map) {
map.addMarker(new MarkerOptions()
.position(new LatLng(10, 10))
.title("Hello world"));
}
https://developers.google.com/maps/documentation/android-api/marker
Related
I do want to get current location with GoogleApiClient with this code below,
#Override
public void onConnected(#Nullable Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null)
{
currentLat = mLastLocation.getLatitude();
currentLon = mLastLocation.getLongitude();
}else
{
Toast.makeText(getApplicationContext(), "Cannot get lat and lon", Toast.LENGTH_SHORT).show();
}
}
then after that i do want to put marker on current location, my problem is mLastlocation still null
#Override
public void onMapReady(GoogleMap googleMap) {
dGoogleMap = googleMap;
if(mLastLocation != null)
{
MarkerOptions marker = new MarkerOptions()
.position(new LatLng(currentLat, currentLon))
.title("My Current Location");
dGoogleMap.addMarker(marker);
dGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(currentLat, currentLon), 16));
}
}
Or this is my fault missunderstand the flow of async, or just my poor logic needs to be improved.
Put below line in your onMapReady method
dGoogleMap.setMyLocationEnabled(true);
how I can get latitude and longitude from setMyLocationEnabled? while my code is this.
I need to use it to zoomin to location,
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0,0)).title("Marker"));
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newLatLng());
mMap.animateCamera(CameraUpdateFactory.zoomBy(13));
}
For getting individual latitude and longitude, the following works for me.
mMap.setMyLocationEnabled(true);
double lat = mMap.getMyLocation().getLatitude();
double longt = mMap.getMyLocation().getLongitude();
Google map location API has the listeners you can get your current location by using this.
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMarker = mMap.addMarker(new MarkerOptions().position(loc));
if(mMap != null){
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
}
};
And then set the listener for the map.
mMap.setOnMyLocationChangeListener(myLocationChangeListener);
My code is totally fine, i want to get user location on the map as soon as the app is opened. But the app just crashes. Also the program is set to update location and add a marker as soon as its changed, nut that's also is not working. Here's the code
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
LocationManager locationManager;
String provider;
#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);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Location location= locationManager.getLastKnownLocation(provider);
double lat =location.getLatitude();
double lng =location.getLongitude();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title("Marker"));
// Add a marker and move the camera
}
#Override
public void onLocationChanged(Location location) {
Double lat = location.getLatitude();
Double lng = location.getLongitude();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 10));
Log.i("Latitude", lat.toString());
}
try This.
getLastKnownLocation returns if location is there in cache otherwise it returns null
add a check there
if(location!=null)
{
double lat =location.getLatitude();
double lng =location.getLongitude();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat,lng)).title("Marker"));
}
2 solution use google play services fusedlocation api for better management with location refer here http://coderzpassion.com/android-location-using-google-play-services/
3 try this to addMarker
public void drawMarker(double lat,double lon)
{
if (mMap != null) {
MarkerOptions marker = new MarkerOptions().position(new LatLng(lat, lon)).title(" Maps Tutorial").snippet("Android Ruler");
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
// Moving Camera to a Location with animation
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude)).zoom(12).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mMap.addMarker(marker);
}
}
for more details refer here http://coderzpassion.com/android-google-maps-v2-tutorial-with-markers/
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));
}
});
I have integrated Google Maps in my Android project. I am getting the view of the map on my device. I want to set the marker to my current location. I have done the following coding but it gives me a Null Pointer Exception on line 43 which is the following line
mMap.addMarker(new MarkerOptions()
.position(new LatLng(location.getLatitude(), location.getLongitude()))
.title("Hello world"));
My codes are as below. Please guide me step by step as to what is going wrong.
public class location extends Activity implements LocationListener {
private GoogleMap mMap;
LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.map_location);
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.the_map)).getMap();
mMap.setMyLocationEnabled(true);
//mMap.addMarker(new MarkerOptions());
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
mMap.addMarker(new MarkerOptions()
.position(new LatLng(location.getLatitude(), location.getLongitude()))
.title("Hello world"));
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
mMap.animateCamera(cameraUpdate);
// locationManager.removeUpdates(this);
}
Try below Code it worked for me..
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_location);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// 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);
LocationListener locationListener = new LocationListener() {
void onLocationChanged(Location location) {
// redraw the marker when get location update.
drawMarker(location);
}
if(location!=null){
//PLACE THE INITIAL MARKER
drawMarker(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, locationListener);
}
}
private void drawMarker(Location location){
googleMap.clear();
LatLng currentPosition = new LatLng(location.getLatitude(),location.getLongitude());
googleMap.addMarker(new MarkerOptions()
.position(currentPosition)
.snippet("Lat:" + location.getLatitude() + "Lng:"+ location.getLongitude()));
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.title("ME"));
}
Ur code seems to be correct. Just check ur location object, it might be null.
#Override
public void onLocationChanged(Location location) {
// Add a marker in Sydney and move the camera
mLocation = location;
LatLng myLocation = new LatLng(mLocation.getLatitude(), mLocation.getLongitude());
mMap.addMarker(new MarkerOptions()
.position(myLocation)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
.title("My Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation));
Log.d("location", "Latitude:" + mLocation.getLatitude() + "\n" + "Longitude:" + mLocation.getLongitude());
}