I'm building an app that allows a user to set a proximity alarm by selecting a marker and clicking on the info window to confirm. I need to be able to get the latitude and longitude from the marker so I can use the coordinates to set up the radius.
googleMap.setOnInfoWindowClickListener(
new OnInfoWindowClickListener(){
public void onInfoWindowClick(Marker marker) {
//click function
Toast.makeText(getBaseContext(),
"Info Window clicked#" + marker.getPosition(),
Toast.LENGTH_SHORT).show();
LocationManager lm;
double lat=0;
double long1=0; //Defining Latitude & Longitude
float radius=3000;
lm=(LocationManager) getSystemService(LOCATION_SERVICE);
Intent i= new Intent("com.example.sleepertrain5.proximityalert"); //Custom Action
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), -1, i, 0);
lm.addProximityAlert(lat, long1, radius, -1, pi);
So far, I've only been able to find marker.getLocation() which doesn't allow direct variable setting. Is there a way to do this?
Have you tried this:
map.setInfoWindowAdapter(new InfoWindowAdapter() {
// Use default InfoWindow frame
#Override
public View getInfoWindow(Marker args) {
return null;
}
// Defines the contents of the InfoWindow
#Override
public View getInfoContents(Marker args)
{
LatLng clickedMarkerLatLng = args.getPosition();
double latitude = clickedMarkerLatLng.latitude;
double longitude = clickedMarkerLatLng.longitude;
....
}
I hope this code helps you :
#Override
public void onMapLongClick(LatLng point) {
Latitude lat = point.getLatitude();
Longitude lng = point.getLongitude();
}
Related
I'm trying to make an app that will use an Place autocomplete fragment in one activity and when I select a place in it, on a click of a button, I'm supposed to open another activity (Google Maps activity) and it's supposed to get the location that I chose in the first one. I've tried passing Longitude and Latitude from Main class to Maps class, but it just crashes my app. Anyone have any idea how to fix?
Thank you in advance!
EDIT: Sample of what I've tried so far:
/*This is the main class where my autocomplete fragment is*/
Double Lat;
Double lang;
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
// Lat = place.getLatLng().latitude;
// lang = place.getLatLng().longitude;
setLang(place.getLatLng().longitude);
setLat(place.getLatLng().latitude);
Log.i(TAG, "Place: " + place.getName());
}
public void setLang(Double langg){
this.lang = langg;
}
public void setLat(Double Latt){
this.Lat = Latt;
}
public Double getLang(){
return lang;
}
public Double getLat(){
return Lat;
}
/* This is the maps class */
MainActivity maAct;
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng place = new LatLng(maAct.getLat(), maAct.getLang());
// LatLng paris = new LatLng(48.8566, 2.3522);
mMap.addMarker(new MarkerOptions().position(place).title("Marker inPlace"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(place));
}
Ok, you may consider to pass the latitude and longitude by Intent.
// MainActivity
Intent intent = new Intent(MainActivity.this, MapActivity.class);
intent.putExtra("lat", Lat);
intent.putExtra("lng", lang);
startActivity(intent);
And..
// Map Activity onMapReady
double lat = getIntent().getDoubleExtra("lat", DEFAULT_LAT);
double lng = getIntent().getDoubleExtra("lng", DEFAULT_LNG);
LatLng place = new LatLng(lat, lng);
mMap.addMarker(new MarkerOptions().position(place).title("Marker inPlace"));
You cannot getValue by maAct, your concept is incorrect.
First if you just
MainActivity maAct;
maAct is not assigned any 'value', so that if you call any methods of maAct, you will get NullPointerException.
Besides, if you really give it a 'value',
// it is totally wrong, just an example only
MainActivity maAct = new MainActivity();
But it is not the same reference so that you cannot get the values you stored before.
What i understand is you want to navigate to the passed latitude and longitude.Here is a sample
String uri = String.format(Locale.ENGLISH, "google.navigation:q=%f,%f", Double.parseDouble(latitude), Double.parseDouble(longitude));
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
if(intent.resolveActivity(context.getPackageManager())!=null)
context.startActivity(intent);
You can find more info like creating markers and all here
Edit:
As per your code you want to set the marker.Here is the steps and sample for a working marker example.
So I've been able to get periodic updates of my current location through the developer android page, making your app location aware. Now, whenever my location changes, I am able to get the latitude and longitude of that location. However, who do i implement this with Google Maps?
This line below implements a button on my map that finds my current location and places a blue dot/marker on it (does not receive periodic updates)
mMap.setMyLocationEnabled(true);
What should I put in my onLocationChanged() event in order for the blue dot to be updated with the new lat and long?
The blue dot and the precision circle are automatically managed by the map and you can't update it or change it's symbology. In fact, it's managed automatically using it's own LocationProvider so it gets the best location resolution available (you don't need to write code to update it, just enable it using mMap.setMyLocationEnabled(true);).
If you want to mock it's behaviour you can write something like this (you should disable the my location layer doing mMap.setMyLocationEnabled(false);):
private BitmapDescriptor markerDescriptor;
private int accuracyStrokeColor = Color.argb(255, 130, 182, 228);
private int accuracyFillColor = Color.argb(100, 130, 182, 228);
private Marker positionMarker;
private Circle accuracyCircle;
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
markerDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.yourmarkericon);
}
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
float accuracy = location.getAccuracy();
if (positionMarker != null) {
positionMarker.remove();
}
final MarkerOptions positionMarkerOptions = new MarkerOptions()
.position(new LatLng(latitude, longitude))
.icon(markerDescriptor)
.anchor(0.5f, 0.5f);
positionMarker = mMap.addMarker(positionMarkerOptions);
if (accuracyCircle != null) {
accuracyCircle.remove();
}
final CircleOptions accuracyCircleOptions = new CircleOptions()
.center(new LatLng(latitude, longitude))
.radius(accuracy)
.fillColor(accuracyFillColor)
.strokeColor(accuracyStrokeColor)
.strokeWidth(2.0f);
accuracyCircle = mMap.addCircle(accuracyCircleOptions);
}
mMap.setMyLocationEnabled(true);
this is simple trick for blue marker of current location and did the trick for me.
This application purposed to get the distance from 2 points of coordinate. The ways is just to click in the map of the position place that you want to count the distance. But there's problem in the point's start, where the application cannot changes the position place.
this is my code:
public class MapsActivity extends FragmentActivity {
// the Google Map object
private GoogleMap mMap;
//ArrayList markerPoints;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// we set the layout for the Activity
setContentView(R.layout.activity_maps);
// the geocoder is instantiated for the first time
geocoder=new Geocoder(this);
// if there isn't a map, it will be created
setUpMapIfNeeded();
}
// LatLng objects store a pair of terrestrial coordinates (latitude and longitude)
private static LatLng STARTING_MARKER_POSITION =new LatLng(3.099465, 101.717111);
/* distanceFrom indicates the starting point to calculate the distance from.
It's initialized with STARTING_MARKER_POSITION
*/
private LatLng distanceFrom= STARTING_MARKER_POSITION;
// line will be drawn at the click event
private Polyline line=null;
// A Geocoder can transform a pair of latitude/longitude into a street address and viceversa.
// We'll use it in the listener
private static Geocoder geocoder=null;
private GoogleMap.OnMapClickListener clickListener=new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(final LatLng pos) {
// this method is called when the user taps the map
// if a line already appears, it's removed
if (line!=null)
line.remove();
// a new line is created
line = mMap.addPolyline(new PolylineOptions()
.add(distanceFrom, pos)
.width(9) // width of the line
.color(Color.BLUE)); // line color
// call the converter object for geocoding invocation and distance calculation
new AddressConverter().execute(distanceFrom, pos);
}
};
#Override
protected void onResume() {
super.onResume();
// the availability of the GoogleMap will be checked before the Activity starts interacting with the user
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// the map is created only it has not been initialized
if (mMap == null) {
// the map is located in the layout
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// if a map exists, we proceed with initialization
if (mMap != null) {
setUpMap();
}
}
}
// Now it's time to configure the map. We can add markers, shapes, event handlers and so on
private void setUpMap() {
// the camera will be positioned according to the new coordinates
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(STARTING_MARKER_POSITION, 14));
// we choose the type of the map: Satellite in this case
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// markerOptions describes the marker we want to place
MarkerOptions markerOptions=new MarkerOptions()
.position(STARTING_MARKER_POSITION)
.draggable(true);
// the marker has to be draggable as we'll move it
// the marker is rendered on the map
mMap.addMarker(markerOptions);
// we define the object to invoke when the marker is dragged
mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener()
{
#Override
public void onMarkerDragStart(Marker arg0)
{
// this method is called when the drag starts
// the operation we need is the cancellation of a preexisting line
if (line!=null)
line.remove();
}
#Override
public void onMarkerDragEnd(final Marker pos)
{
// we get the final position of the marker
distanceFrom=pos.getPosition();
}
#Override
public void onMarkerDrag(Marker arg0)
{
// operations performed during the movement. Nothing to do
}
});
// the callback to invoke is set
mMap.setOnMapClickListener(clickListener);
}
// we want to know which address corresponds to this location
// we use AsyncTask to perform slower operations on a separate thread
private class AddressConverter extends AsyncTask<LatLng,Void,String>
{
// The ProgressDialog window we'll show during the calculation
private ProgressDialog progress=null;
// this method is called before the background job starts. It works on the main thread
#Override
protected void onPreExecute() {
// ProgressDialog is shown
progress= ProgressDialog.show(MapsActivity.this,"Distance calculator","We are calcultating the distance...", true,false);
}
// this method works on a separate thread
// it performs geocoding operations to retrieve the address of the points and calculates the distance in meters between them
#Override
protected String doInBackground(LatLng... params) {
float[] distance=new float[1];
try {
// the Location class contains what we need to calculate distances
Location.distanceBetween(params[0].latitude,params[0].longitude,params[1].latitude,params[1].longitude,distance);
// geocoding operations
List<Address> fromResult=geocoder.getFromLocation(params[0].latitude,params[0].longitude,1);
List<Address> toResult=geocoder.getFromLocation(params[1].latitude,params[1].longitude,1);
// the message informs the user about the distance from the marker to the point selected with the click
// if we have got both the addresses, we use them to compose the message, otherwise we show only the distance
if (fromResult.size()>0 && toResult.size()>0)
{
// ((TextView) findViewById(R.id.tvDuration)).setText(route.duration.text);
return "The distance between " + getAddressDescription(fromResult.get(0)) + " and " + getAddressDescription(toResult.get(0)) + " is " + Math.round(distance[0]) + " meters";
}
else
return "The distance is " + Math.round(distance[0]) + " meters";
}
catch (IOException e) {
return "The distance is " + Math.round(distance[0]) + " meters";
}
}
#Override
protected void onPostExecute(String message)
{
if (progress!=null)
progress.dismiss();
// The builder of the window is instantiated
AlertDialog.Builder builder=new AlertDialog.Builder(MapsActivity.this);
builder.setTitle("Distance");
builder.setMessage(message);
// the Alert dialog appears
builder.show();
}
}
// this method only formats the message with addresses
private String getAddressDescription(Address a)
{
String city=a.getLocality();
String address=a.getAddressLine(0);
return "'"+address+"' ("+city+")";
}}
Use distanceBetween() method, It will give you exact distance in meters.
Location.distanceBetween(double startLatitude, double startLongitude,
double endLatitude, double endLongitude, float[] results);
I have this code:
Location newLocation = new Location(LocationManager.GPS_PROVIDER);
Location oldLocation = new Location(LocationManager.GPS_PROVIDER);
float distanceTravelled=0;
onLocationChanged:
#Override
public void onLocationChanged(Location location)
{
oldLocation.set(newLocation);
startactivity();
distanceTravelled+=newLocation.distanceTo(oldLocation);
String stringDistance= Float.toString(distanceTravelled);
TextView distance = (TextView) findViewById(R.id.textDistance);
distance.setText(stringDistance);
}
startactivity:
public void startactivity()
{
GPSTracker gps = new GPSTracker(Live.this);
if(gps.canGetLocation())
{
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Location is: \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
newLocation.setLatitude(latitude);
newLocation.setLongitude(longitude);
}
else
{
gps.showSettingsAlert();
}
}
GPSTracker is a separate class which gets the current latitude and longitude (it is working fine!).
GPS updates at min. distance 5 metres and min. time 5 seconds.
Here is my full GPSTracker class: GPSTracker.java
I have added the three permissions in the manifest: fine,coarse and internet.
My problem is the textview inside onLocationChanged never gets changed.
What is the problem? Is onLocationChanged not getting called or there is some logical error (distance always remains zero)?
And how to fix that?
Your function is
public void onLocationChanged(Location location)
but you are not using that parameter anywhere in the function.
It looks like you should add
newLocation.set(location);
after the first line of your function.
At the moment you are calculating the distance between the starting point and itself, and that will always be 0.
i am really stuck on this:
I have longitude / latitude points to draw on a google map within an android app.
Therefor I created a class extending Overlay...
I get the current longitude/latitude portion of view via:
GeoPoint topLeft = proj.fromPixels(0, 0);
GeoPoint bottomRight = proj.fromPixels(width-1, height-1);
int topLat = topLeft.getLatitudeE6();
int topLon = topLeft.getLongitudeE6();
int bottomLat = bottomRight.getLatitudeE6();
int bottomLon = bottomRight.getLongitudeE6();
The following works (only latitudes):
if(latLon[0] >= bottomLat && latLon[0] <= topLat){ // do something; }
but this does not work (longitudes):
if(latLon[1] >= topLon && latLon[1] <= bottomLon) { // do something; }
latLon[0] is the latitude I want to check
latLon[1] is the longitude I want to check
Anybody an idea?
Greetz!
Longitude numbers are negative from the 0 meridian in England, westward. They're negative in North America and South America.
Use a google map and insert your marker on it.
See below :
public class MapActivity extends GeolocationActivity implements GoogleMap.OnInfoWindowClickListener{
private final String TAG = "MapFragment";
private MapView _mapView;
private GoogleMap _gmap;
/**
* the logo of the marker on the map
*/
private Bitmap _littlePin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
_mapView = (MapView) findViewById(R.id.location_map);
_mapView.onCreate(savedInstanceState);
_gmap = _mapView.getMap(); // initalise the map
if (_gmap != null)
{
setUpMap();
}
}
/**
* set up the map; Add the market on it with a blue dot for the location of the user in real time
* #return false if something goes wrong, true otherwise
* _latitude = latitude of the user, get from the GeolocationActivity
* _longitude = longitude of the user, get from the GeolocationActivity
*/
private boolean setUpMap()
{
// Gets to GoogleMap from the MapView and does initialization stuff
_gmap.getUiSettings().setMyLocationButtonEnabled(false);
_gmap.setMyLocationEnabled(true);
if (_gmap == null) {
Toast.makeText(this, "Google Maps not available", Toast.LENGTH_LONG).show();
return false;
}
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
MapsInitializer.initialize(this);
BitmapDrawable bitmapDrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.pin); // file stored in /res/drawable/
Bitmap bitmap = bitmapDrawable.getBitmap();
_littlePin = Bitmap.createScaledBitmap(bitmap, 96, 96, false); // 96/96px
_gmap.setOnInfoWindowClickListener(this);// add listener on this class
// here the _lat and _long should be the user of this cafe, at the moment I am using the one of the user
this.addMarker("Cafe", "Best cafe in London", new LatLng(_latitude, _longitude));
// camera, 13 if the zoon, you can change it manually, or dynamically in order to see all your markers
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(_latitude, _longitude), 13);
_gmap.animateCamera(cameraUpdate); // zoom effect
return true;
}
/**
* Add markers on the map view
* #param title title of place / marker
* #param description short description
* #param position geposition, LatLng object, filled with latitude and longitude.
*/
private void addMarker(String title, String description, LatLng position)
{
_gmap.addMarker(new MarkerOptions()
.position(position)
.title(title)
.snippet(description)
.icon(BitmapDescriptorFactory.fromBitmap(_littlePin)));
}
/**
* The user click on the marker on the map, this callback is called
* #param marker clicked marker
*/
#Override
public void onInfoWindowClick(Marker marker) {
Log.d(TAG, "onMarkerClick " + marker.getTitle());
}
#Override
public void onResume() {
_mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
_mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
_mapView.onLowMemory();
}
}
Here is a good example which gonna help you.
and the github with the code sample is here.
Hope this help.