How to get Current Lat Lng position on GMAPS API V3? - android

I'm trying to calculate my route, from my current position to the specific location (var: end). How I suppose to get my LatLng from my current position ? Thx
Here's my Code :
function calcRoute() {
var start = "How to get this LatLng ?";
var end = new google.maps.LatLng(-6.28529,106.871542);
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}

If you have a Location object (lets call it location), all you need to do is LatLng mLatLng = new LatLng(location.getLatitude(), location.getLongitude()) and you will have a LatLng object. location.getLatitude() returns a double corresponding to the latitude in degrees and location.getLongitude() returns the same but for longitude. See the documentation for more details: http://developer.android.com/reference/android/location/Location.html

Related

.cameraPosition.target does not provide center of current view

I have a location marked in google map. The user has the option to change this location by dragging the map. I am using camera position to get the new location.Here is my code to get the original location:
mMap = googleMap
val addkey = intent.getStringExtra("address")
var addlocation = getLocationFromAddress(addkey) as LatLng
var mapLocation = CameraUpdateFactory.newLatLngZoom(addlocation, 18.0f)
mMap.animateCamera(mapLocation)
The getLocationFromAddress code is working fine.
The user then drags to a new location, clicks a button when done and upon confirmation the new location is accepted. I am trying to get the Latitude Longitude of the current camera position using the single line code:
addlocation = mMap.cameraPosition.target
But the code continues to return the Lat Long of old view. Where am I wrong?
Implement it like this -
private GoogleMap.OnCameraIdleListener onCameraIdleListener;
then use the camera listener to get the latitude longitude from the camera center position like this -
onCameraIdleListener = new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
LatLng latLng = mMap.getCameraPosition().target;
Geocoder geocoder = new Geocoder(MapsActivity.this);
try {
List<Address> addressList = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if (addressList != null && addressList.size() > 0) {
String locality = addressList.get(0).getAddressLine(0);
String country = addressList.get(0).getCountryName();
if (!locality.isEmpty() && !country.isEmpty())
resutText.setText(locality + " " + country);
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
Getting the address is an addition thing added here. Use it if you need it.

How to update the blue dot marker for current location in MapView in Android

I have a fragment which when normally launched shows a mapview with current user location shown as blue dot marker. I have a feature to launch this screen from another place and can pass latitude and longitude values. Based on these values, I update the latitude and longitude of "MapboxMap". The location is updated on map and camera zooms to it but blue dot marker still shows as user current location. How can I update the blue dot marker to be shown as new location given by latitude and longitude value:
My code to update location:
private void goToUserLocation() {
double requestedLatitude = 0;
double requestedLongitude = 0;
if (mapboxMap == null || !getUserVisibleHint()) {
return;
}
if (!DeviceUtil.isLocationServiceEnabled(getContext().getApplicationContext())) {
showLocationDisabledSnackbar();
return;
}
enableUserLocationMarker();
Location location = mapboxMap.getMyLocation();
//Get the requested coordinates if it exists
if(location != null) {
try {
Uri intentData = getActivity().getIntent().getData();
if (null != intentData) {
String latitude = intentData.getQueryParameter("lat");
String longitude = intentData.getQueryParameter("lon");
if (!TextUtils.isEmpty(latitude) && !TextUtils.isEmpty(longitude)) {
requestedLatitude = Double.parseDouble(latitude);
requestedLongitude = Double.parseDouble(longitude);
if ((requestedLatitude >= -90 && requestedLatitude <= 90) &&
(requestedLongitude >= -90d && requestedLongitude <= 90d)) {
location.setLatitude(requestedLatitude);
location.setLongitude(requestedLongitude);
}
}
}
}catch (NumberFormatException ex) {
}
finally {
goToLocation(location);
}
}
fetchNearbyPages();
}
Any help is appreciated.
Hi hope this will help.
First, override the onLocatioChanged method and pass the updated location to separate created setCameraToCurrentPosition method. ex. is as follows:-
public void onLocationChanged(Location location) {
setCameraToCurrentPosition(Location location);
}
private void setCameraToCurrentPosition(Location location) {
setCameraPosition(new LatLng(location.getLatitude(), location.getLongitude()), 16, 6500);
// Here you need to add the marker to current position of user on map.
}

Update and delete specific marker in Google Map

I am displaying the location of buses in google map where I am getting the location from the bus database table on the server. I am facing problem to delete or to update their locations on google map since a new marker is always being created when the longitude and latitude change in the bus table. How can I delete and update specific Marker in Google Map?
I appreciate any help.
Code:
private void gotoLocation(double lat, double lng, String route_direct) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
final float zoom = 11;
LatLng ll = new LatLng(lat, lng);
if (lat != 0 && lng != 0 && !route_direct.isEmpty()) {
MarkerOptions markerOpt = new MarkerOptions().title(route_direct)
.position(ll).visible(true);
Marker marker = map.addMarker(markerOpt);
marker.showInfoWindow();
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
map.moveCamera(update);
}
}
I solved in this way. I created HashMap for markers.
Sample,
HashMap<String, Marker> markerlist = new HashMap<>();
markerlist.put(route_direct, yourmarker);//add marker to list
markerlist.get(route_direct);//get marker from list
Then in your update process, try this code
if(markerlist.containsKey(route_direct)){
Marker marker = markerlist.get(route_direct);
//update marker
}else{
//add marker or do anything
}
but to use this flow, you need to have unique data for marker such as marker id.
Hope this will help you. Good luck.
Here we have used on our project in didTap marker delegates, We have created two functions one is Create marker and second one is delete marker code is given below in IOS swift
1.CreateMarker function call when you get Response from APIs
2.DeleteMarker call when you want to delete marker from map
//MARK: CreateMarker
func CreateMarker(TripLocation:[RECDATA])
{
//let path = GMSMutablePath()
for i in 0..<TripLocation.count
{
// Marker icon
var image = UIImage(named: "ic_greenMark")
// Get location coordinate
let locationTujuan = CLLocation(latitude: Double(TripLocation[i].facilityLatitude ?? 0.0) , longitude: Double(TripLocation[i].facilityLongitude ?? 0.0) )
image = UIImage(named: "ic_greenMark")
// create marker
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(locationTujuan.coordinate.latitude, locationTujuan.coordinate.longitude)
// marker.title = titleMarker
marker.icon = image
marker.map = MapView
let camera = GMSCameraPosition.camera(withLatitude:CLLocationDegrees(TripLocation[i].facilityLatitude!), longitude: CLLocationDegrees(TripLocation[i].facilityLongitude ?? 0.0), zoom: 8)
MapView.camera = camera
// append marker into markers array to show all marker in map
markers.append(marker)
}
}
//MARK: DeleteMarker
func DeleteMarker(marker:GMSMarker)
{
// Create Temp Object array
var Tempmarkers = [RECDATA]()
//check marker is exist or not
for obj in arrayRECDATA
{
let lat = Double(obj.facilityLatitude!)
let log = Double(obj.facilityLongitude!)
// remove marker from object array
if marker.position.latitude != lat && marker.position.longitude != log
{
Tempmarkers.append(obj)
}
}
// store temp array into original array
arrayRECDATA = Tempmarkers
// clean all marker and reload
MapView.clear()
CreateMarker(TripLocation: arrayRECDATA)
}
Thank you :)
Define variable for each marker like
Marker m1;
Marker m2;
etc.
And do whatever operation on specific marker using that variable. To delete the specific marker
m1.delete ();
m2.delete ();
Something like this, you can try and let me know if you face any issue.

How to get the latitude and longitude of location where user taps on the map in android

In my Android application, I'm using google maps v2 to show map by getting the latitute and longitude of the device's current location And I'm showing pin on that location.
Now when user clicks or taps on any other location on the map, then I have to get that points latitude and longitude and i have to set the pin at that location.
Could you please tell me how get the latitude and longitude of the user taps/clicks location.
An example of what i use. Change it accordingly for your needs. I use it with long press.
map.setOnMapLongClickListener(new OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng point) {
map.addMarker(new MarkerOptions().position(point).title("Custom location").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));enter code here
}
});
the LatLng point contains the coordinated of the longpress
Try to use google-maps v2 built-in method.
map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng position) {
Toast.makeText(context,position.latitude+" : "+position.longitude,Toast.LENGTH_SHORT).show();
}
});
Try the following.
Write a class which derives from the Overlay class and override the onTap() method. Then you can add your overlay to the your MapView. A GeoPoint object, which represents the position of you tap, is passed to the onTap() method when you tab somewhere on the map.
OR
The modern answer here, using Android Maps v2, is to use OnMapClickListener, which gives you the LatLng of a tap on the map.
// Setting onclick event listener for the map
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
//Get LatLng from touched point
double touchLat=point.latitude;
double touchLong=point.longitude;
///here is reverse GeoCoding which helps in getting address from latlng
try {
Geocoder geo = new Geocoder(MainActivity.this.getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(touchLat,touchLong, 1);
if (addresses.isEmpty()) {
Toast.makeText(getApplicationContext(),"Waiting for Location",Toast.LENGTH_SHORT).show();
}
else {
if (addresses.size() > 0) {
address =addresses.get(0).getFeatureName()
+ ", " + addresses.get(0).getLocality()
+ ", " + addresses.get(0).getAdminArea()
+ ", " + addresses.get(0).getCountryName();
Toast.makeText(getApplicationContext(), "Address:- " +address, Toast.LENGTH_LONG).show();
}
// draws the marker at the currently touched location
drawMarker(point,"Your Touched Position",address+"");
}
}
catch (Exception e) {
e.printStackTrace(); // getFromLocation() may sometimes fail
}

Google places retrieves same value in all the execution

I was working with a Google map v2 oriented android project. In my program i retrieves the name,vicinity,latitude&longitude from the places api while touching on the info boxes of the markers.But it every time retrieves the same value.But it shows the correct result in the info boxes.How to solve this bug .Someone please solve this.
Code
for(final Place place : nearPlaces.results){
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting latitude of the place
double latitude = place.geometry.location.lat;
double longitude = place.geometry.location.lng;
// Getting name
String NAME = place.name;
// Getting vicinity
String VICINITY = place.vicinity;
//final String REFERENCE = place.reference;
final String slat = String.valueOf(latitude);
final String slon = String.valueOf(longitude);
LatLng latLng = new LatLng(latitude, longitude);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
//This will be displayed on taping the marker
markerOptions.title(NAME + " : " + VICINITY);
markerOptions.icon(bitmapDescriptor);
// Placing a marker on the touched position
mGoogleMap.addMarker(markerOptions);
mGoogleMap.setOnInfoWindowClickListener(
new OnInfoWindowClickListener(){
#Override
public void onInfoWindowClick(Marker arg0) {
// TODO Auto-generated method stub
arg0.hideInfoWindow();
alert.showpickAlertDialog2(PlacesMapActivity.this, slat, slon, place.reference,KEY_TAG);
}
}
);
}
LatLng mylatLng = new LatLng(mylatitude, mylongitude);
// Creating CameraUpdate object for position
CameraUpdate updatePosition = CameraUpdateFactory.newLatLng(mylatLng);
// Creating CameraUpdate object for zoom
CameraUpdate updateZoom = CameraUpdateFactory.zoomBy(10);
// Updating the camera position to the user input latitude and longitude
mGoogleMap.moveCamera(updatePosition);
// Applying zoom to the marker position
mGoogleMap.animateCamera(updateZoom);
What you are doing wrong is setting OnInfoWindowClickListener in a loop.
Take that code outside and retrieve slat and slon from Marker arg0 by using getPosition.
There are other people who are struggling with this issue as well.
You are assuming that the slat and slong values are going to carry through to the onInfoWindowClick() method, but you are always getting the same values there.
Here is a discussion some other folks were having on this topic.

Categories

Resources