I want to show a route between the user's current location and the location he entered in the searchview. Here is my code for the onQueryTextSubmit method
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
try
{
if(direction.isChecked() == false)
{
gc = new Geocoder(this);
addresses = gc.getFromLocationName(query,5);
String add = "";
if (addresses.size() > 0)
{
p = new GeoPoint(
(int) (addresses.get(0).getLatitude() * 1E6),
(int) (addresses.get(0).getLongitude() * 1E6));
mc.animateTo(p);
mc.setZoom(9);
mapView.invalidate();
searchView.clearFocus();
}
else
{
Toast.makeText(this, " Location not found.",
Toast.LENGTH_LONG).show();
}
return true;
}
else
{
// draw a route between the locations
return true;
}
}
catch(IOException ex)
{
}
return false;
}
what is the simplest way to do it? (examples will help me understand more)
Thank You
Once you have your destination GeoPoint you could do an http request to google in this address:
String url = "http://maps.google.com/maps?f=d&hl=es&saddr="+ origin +"&daddr=" + destination + "&ie=UTF8&om=0&output=dragdir";
being origin and destination (latitude, longitude) points.
For example, this request gives you this json:
{tooltipHtml:" (86,4 km / 55 minutos)",polylines:[{id:"route0",points:"wa{uFt|kUoAkE??jDyE??uFuLqFaH??mAl#gAZ??q#[Yg#KwCBkATq#X[bCu#??tMsBrIuBrDoA~J}EbC{#pCy#dIeA`JBrDThd#nFpDRnTkAdBGVFhRyC`McA|KkAzCK|CP??lA~#NZHn#I~#Q`#c#\\[Hu#KYWUe#Gc#D{BnG}a#`Kcb#|A}JvAkOXmHDgFKcMMmDkBgW??SaCEoFBaCb#mH`AwGdE_Qh#sCf#}Db#yGFcFIqE]iGcAkLUyGB{K^aHf#_EfC_PtAqOlB}X|AiNrCyTnE{WjDqOtCqK~DoMhHoSvX}u#~KeYpI}VrSkk#zBiJ`#_Ct#oG`#mGPoGCcLMoDq#wHiCaSe#qE_BgTMuEEoIDsJxA_`#DcHGoCw#iJkAoHsCwN_AcHk#mG]wGOcLLeJZiG\\gEr#kGhBeKpB{H~#uCvB{F~CuGbBuCdE_GlE}ElBgBfQeNpCsCtCmDtCoEnBsD~BmFdB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IK_EL}Db#qDbAqD|#uBjOuVxIgQ~DsK|AuFpAaHt#_F`AqK^gL#yG_#u\\HeHNwEv#oKx#eHbDgPzDuNlAuD~F{O~BoF`AiBnBoCzFwF~CoDlBcEfAaD|Kc_#r#yBtAgD`AaBbHsJ|CsCrP_LpBwB`BqChAgDr#yDR}BhBs\\VuBx#kDlAyCdBkCdDqClQcHlC_B|CuDlJcQbA{AlAqA~_Ags#lSiSrBaCfOiWtVs]z`#_s#zMiVvAuBzPyTfRg[rBuD`B_EtCkIvKs]nCaHlEuIfHaMbMoRv[kd#lEqFfo#qp#|C{Cf#[bQsHrBoA~AsAbAqA|GsMtBiC|B_BlHwD`Au#vA{AnAmB|#wB|#eDbEmThAsEh#_BzAcDnKmP~z#}kA|AcBbDcCvFyBvSgGnBa#~TiGnNmC|DkB??xCoApDU|#UtAeAZm#\\gARkBQeK#i#^cC??pBkHvFy]Pm#ZCHQVuAAc#hAyC~#m#dBYzPq#??Jd#NJR?VSBi#pBq#l#e#d#e#jAoB\\_A\\_BnBePTCN[A[SWtIsr#Aq#VCLSAg#OQpDwX^kE??rAJrB]p#[tAuA",levels:"BBBBB?BB?BB???#??BB??????#???#???????BB??#???#????#???#????BB???#????#??????#??????#??#????#??A???#????#????#?????#????A?????#?????#???#???#?????#???A?#???#????#???#???#???A?????#????#??????????#??????#????#?????#???#???#?????BB??#???#??????#????#??#???#??A???#?????#????#?#??????????#???A???#?????#?????#???#?????#???????#??#???#???#????#???#????#???#???#??#????A????#????#????#?????#???#???#?????#??????#???#???#?????#??#???#????#???#?????#??????A???#???#??#??????#????#??#?##???#???#???#??????#?#??#????BB????#????BB???????#??BB??????#???#????????????BB???B",numLevels:4,zoomFactor:16}]}
The String with name points is the polyline you have to draw on your map. But before drawing you have to decode it. Take a look here for that duty.
Once you have your GeoPoint list, you can draw it on your map. For that you need an overlay if you're using google api v1. I'd recommend you to have a look into api v2. It's easier to add polylines to map objects via the addPolyline method in GoogleMap class and PolylineOptions.
Hope that helps.
by two ways we can draw route on map.
1.use Map OverLay concept in android
2.use this url
http://maps.google.com/maps?&saddr=from latitude value,from longitude value &daddr= to latitude value,to longitude value
Related
Hi I want place markers on all shoppers stop stores which are near to user current location. I am using following code
currently I am getting only 2 locations, I want set some radius and want to display all the stores also.
private class GeocoderTask extends AsyncTask<String, Void, List<Address>> {
#Override
protected List<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 10);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
}
// Clears all the existing markers on the map
googleMap.clear();
// Adding Markers on Google Map for each matching address
for(int i=0;i<addresses.size();i++){
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
googleMap.addMarker(markerOptions);
// Locate the first location
if(i==0)
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}
but unable to get relevant results. Help me.
You should have a look at nearby search of Places API web service.
To make your life easier you can also use the Java Client for Google Maps Services located at github:
https://github.com/googlemaps/google-maps-services-java
Follow documentation of the Java Client library and you should be able to search nearby places for given location and radius.
I hope this helps!
Hi I am a bit new to android and I have been wanted to develop an android app which is supposed to show the current location of the user on a map like google map in offline mode. Can I show the location with just GPS and without Internet connection ? Needless to say that this offline thing is vitally important for me. Any help would be appreciated. Tnx in advance
You can get the GPS location (although it will be less precise without GSM tower localisation). However, the map part may be tricky. You can use the Google Maps API in your app, like MapActivity, but the map itself has to be downloaded from the web.
So you will need some custom solution for this, probably through a different map provider than Google Maps.
You may be able to do it a bit differently - obtain the location in your app and then open Google Maps with an Intent, passing the received coordinates. This should allow the user to use any offline-stored maps they may have.
You can get raw NMEA data from GPS via NmeaListener or better OnNmeaMessageListener (IMHO it more complex), and parse RMC sentence like this:
public class CustomNmeaListener implements GpsStatus.NmeaListener{
private GoogleMap mGoogleMap;
private Marker mMarkerPosition = null;
private BitmapDescriptor mMarkerMoveDescriptor;
private BitmapDescriptor mMarkerStopDescriptor;
public CustomNmeaListener(GoogleMap googleMap, int markerMoveResource, int markerStopResource){
this.mGoogleMap = googleMap;
mMarkerMoveDescriptor = BitmapDescriptorFactory.fromResource(markerMoveResource);
mMarkerStopDescriptor = BitmapDescriptorFactory.fromResource(markerStopResource);
}
#Override
public void onNmeaReceived(long timestamp, String nmea) {
double latitude;
double longitude;
float speed;
float angle;
// parse NMEA RMC sentence
// Example $GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A
// nmea [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]
if (nmea.startsWith("$GPRMC")) {
String[] nmeaParts = nmea.split(",");
// if RMC data valid ("active")
if (nmeaParts[2].equals("A")) {
latitude = parseLatitude(nmeaParts[3], nmeaParts[4]);
longitude = parseLongitude(nmeaParts[5], nmeaParts[6]);
speed = parseSpeed(nmeaParts[7]);
angle = parseAngle(nmeaParts[8]);
// remove marker on "old" position
if (mMarkerPosition != null) {
mMarkerPosition.remove();
}
MarkerOptions positionMarkerOptions;
if (speed > 0) {
positionMarkerOptions = new MarkerOptions()
.position(new LatLng(latitude, longitude))
.icon(mMarkerMoveDescriptor)
.anchor(0.5f, 0.5f)
.rotation(angle);
} else {
positionMarkerOptions = new MarkerOptions()
.position(new LatLng(latitude, longitude))
.icon(mMarkerStopDescriptor)
.anchor(0.5f, 0.5f)
.rotation(0);
}
mMarkerPosition = mGoogleMap.addMarker(positionMarkerOptions);
}
}
}
static float parseLatitude(String lat, String sign) {
float latitude = Float.parseFloat(lat.substring(2)) / 60.0f;
latitude += Float.parseFloat(lat.substring(0, 2));
if(sign.startsWith("S")) {
latitude = -latitude;
}
return latitude;
}
static float parseLongitude(String lon, String sign) {
float longitude = Float.parseFloat(lon.substring(3)) / 60.0f;
longitude += Float.parseFloat(lon.substring(0, 3));
if(sign.startsWith("W")) {
longitude = -longitude;
}
return longitude;
}
static float parseSpeed(String knots) {
float speed;
try {
speed = Float.parseFloat(knots);
} catch (Exception e) {
speed = 0;
}
return speed;
}
static float parseAngle(String ang) {
float angle;
try {
angle = Float.parseFloat(ang);
} catch (Exception e) {
angle = 0;
}
return angle;
}
}
and set RMC sentence interval on requestLocationUpdates() call
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
<your_update_interval>,
LOCATION_DISTANCE,
this
);
} catch (java.lang.SecurityException ex) {
Log.d(TAG, "fail to request location update, ignore", ex);
}
And for map service you should use custom solution, because, even for offline maps Google Maps need Internet connection at least for MAPS API KEY check. As first approach you can use simple ImageView with map screenshot.
I have the address to certain location in terms of a string. However i want to convert this address to Lattitude and Longitude. So i used the code given below to convert into geopoint. But this geopoint is not getting added to the map. The map always shows the default map thats the entire world.
public GeoPoint getLocationFromAddress(String strAddress) {
Geocoder coder = new Geocoder(this);
List<Address> address;
GeoPoint p1 = null;
try {
address = coder.getFromLocationName(strAddress, 5);
if (address == null) {
return null;
}
Address location = address.get(0);
location.getLatitude();
location.getLongitude();
p1 = new GeoPoint((int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
return p1;
} catch (IOException e) {
e.printStackTrace();
return p1;
}
}
Im new with maps and am not sure what Im doing wrong. Any suggestions?
Now that you know the latitude and longitude, you forgot to update the map to the specific location. You can do it like this:
int zoomNiveau = 15;
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), zoomNiveau));
With this code, the map will go to the location of the address. But you need to create a Marker and add it to the map if you want a Marker.
More info about the markers: https://developers.google.com/maps/documentation/android/marker
I use below code to search on google map android
// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{
#Override
protected List<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Log.d("bagibagi","doInBackground");
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocationName(locationName[0], 1);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(List<Address> addresses) {
Log.d("bagibagi","onPostExecute");
search = "";
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found OR you use this several time", Toast.LENGTH_SHORT).show();
}
else
{
// Adding Markers on Google Map for each matching address
for(int i=0;i<addresses.size();i++){
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
markerOptions = new MarkerOptions();
//markerOptions.icon(icon);
markerOptions.position(latLng);
markerOptions.title(addressText);
//map.addMarker(markerOptions);
Toast.makeText(getApplicationContext(), addressText, 1).show();
// Locate the first location
if(i==0){
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng) // Sets the center of the map to Mountain View
.zoom(13)
// 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));
}
}
}
}
}
how i can change .zoom(13) for a city search or a Country name search.
for example when user search a country map must zoom smaller than search a city.
below image show you thing that i want.
You can use Google Places API to obtain the Viewport of particular place.
Make request to this url: http://maps.googleapis.com/maps/api/geocode/json?address=YOUR-COUNTRY-OR-CITY&sensor=true
In the JSON response you will find the following keys:
geometry:{
bounds:{
northeast:{
lat:40.501368,
lng:-79.8657231
},
southwest:{
lat:40.3613689,
lng:-80.0952779
}
},
location:{
lat:40.44062479999999,
lng:-79.9958864
},
location_type:"APPROXIMATE",
viewport:{
northeast:{
lat:40.501368,
lng:-79.8657231
},
southwest:{
lat:40.3613689,
lng:-80.0952779
}
}
}
Either go for "geometry" key data or "viewport"
Create new LatLngBounds (LatLng southwestParsedCoordinate, LatLng northeastParsedCoordinate) object and move the camera to the that bound object
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 10);
I have this problem.
I want to show a specific location on maps in android. Like if user has entered India in Edit text, then how can i show INDIA on Map. I basically want to know how to get the latitude and longitude of any location.
Please help
My Code:
public class Map extends Activity{
private GoogleMap map;
private LatLng myLoc;
#SuppressLint("NewApi") protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
Intent i=getIntent();
String loc=i.getStringExtra("loc");
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName(
loc, 5);
if (addresses.size() > 0) {
myLoc = new LatLng(
(int) (addresses.get(0).getLatitude() * 1E6),
(int) (addresses.get(0).getLongitude() * 1E6));
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(myLoc, 14);
map.animateCamera(update);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
It is not Working. Please Help
It seems that Geocoder functions are blocked and use network. Because of onCreate is running on main thread, you can get this error(in older versions of android). Thus, you have to create AsyncTask and move geocoder's function to AsyncTask.doInBackground().
And after, in AsyncTask.onPostExecute() you should perfom the other operations with google map. (It will be on main thread in this case, how it must be)
Use
map.setMyLocationEnabled(true);
A blue circle will be appeared on map. It will show the current location.
When you select India from edittext call this function:
public void showSelectedCountry(String countryName) {
if (countryName.equals("India")) {
LatLngBounds boundsIndia = new LatLngBounds(new LatLng(23.63936, 68.14712), new LatLng(28.20453, 97.34466));
int padding = 0; // offset from edges of the map in pixels
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(boundsIndia, padding);
mMap.animateCamera(cameraUpdate);
}
}