how to draw paths on actual roads between two location android - android

I want to draw a path between two locations using on android google map.I have tired this code
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
if (cursor.moveToFirst()) {
do {
// latitude and longitude
double latitude = 0.00;
double longitude = 0.00;
Log.i("lat", cursor.getString(10));
Log.i("lat", cursor.getString(11));
try {
latitude = Double.parseDouble(cursor.getString(10));
} catch (Exception e) {
}
try {
longitude = Double.parseDouble(cursor.getString(11));
} catch (Exception e) {
}
if (latitude == 0.00 || longitude == 0.00) {
} else {
i++;
LatLng point = new LatLng(latitude,longitude);
options.add(point);
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title(cursor.getString(1));
}
}
while (cursor.moveToNext());
}
cursor.close();
googleMap.addPolyline(options);
but i got straight line.like this
I want to get paths on actual roads.
Thanks..!!

If you want to draw a polyline between 2 points and following road, you can try with the library Google-Directions-Android
You can add the library on gradle with compile 'com.github.jd-alexander:library:1.0.7'
You can use all your point (Latlng) and use them into the waypoint method.
Routing routing = new Routing.Builder()
.travelMode(/* Travel Mode */)
.withListener(/* Listener that delivers routing results.*/)
.waypoints(/*waypoints*/)
.build();
routing.execute();

Related

all areas latitude and longitude between route defined

I am working on google map app.when i define a route For example from city one to city two ..then how can i get the latitude and longitude of all places coming between city one and city two.
destinationid= (EditText) findViewById(R.id.destinationid);
String clocation = destinationid.getText().toString();
List<Address> addressList=null;
if(clocation!= null || clocation!="")
{
Geocoder geocoder=new Geocoder(this);
try {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("google.navigation:q="+clocation+""));
startActivity(intent);
addressList= geocoder.getFromLocationName(clocation,1);
}
catch (IOException e)
{
e.printStackTrace();
}
Address address= addressList.get(0);
LatLng latLng=new LatLng(address.getLatitude(),address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Current Location "));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.addMarker(new MarkerOptions().position(latLng).title("Current Location "));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15.0f));
mMap.animateCamera(CameraUpdateFactory.zoomIn()); mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null); CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng)
.zoom(15)
.bearing(150)
.tilt(70)
.build();
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mMap.setTrafficEnabled(true);
}'
To answer your first question in comment above,
1] to show any particular point B on your route you can use markers, this is a feature of google maps API, more details about this you can find here.
2] to check anyone is in your radius you can use Geo fence API. you can find more details here.

Showing current location in offline mode with gps

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.

Android Google map shows black screen before loading

I have an application with an initial window with three buttons. When I click on one of them, I start a progress dialog while I am loading a Google Map V2 and drawing some markers on it.
In the onMapReady callback I dismiss the progress dialog:
#Override
public void onMapReady(final GoogleMap map) {
Log.i(MyMoneyBackActivity.TAG, "ShopsMapActivity onMapReady");
GMap = map;
if (needsInit) {
CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng(CAMERA_LAT,
CAMERA_LNG));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(12f);
map.moveCamera(center);
map.animateCamera(zoom);
}
// Enabling MyLocation Layer of Google Map
map.setMyLocationEnabled(true);
// Clears all the existing coordinates
map.clear();
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
provider = mLocationManager.getBestProvider(criteria, true);
// Get best last location measurement
mBestReading = bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);
mLocationManager.requestLocationUpdates(provider, 20000, 0, this);
Log.i(MyMoneyBackActivity.TAG, "Map");
Geocoder geoCoder = new Geocoder(ShopsMapActivity.this, Locale.getDefault());
if ( geoCoder.isPresent() )
Log.i(MyMoneyBackActivity.TAG, "Geocoder available");
else
Log.i(MyMoneyBackActivity.TAG, "Geocoder NOT available");
// Add a marker for every shop
for (ShopElement rec : MyMoneyBackActivity.shopElementsList) {
//String addressStr = "Aquileia 39,Udine,Italy";
String addressStr = rec.getaddress() + "," + rec.getcity() +",Italy";
Log.i(MyMoneyBackActivity.TAG, "addressStr -" + addressStr + "-");
try {
List<Address> addresses = geoCoder.getFromLocationName(addressStr, 1);
if (addresses.size() > 0) {
latitude = addresses.get(0).getLatitude();
longitude = addresses.get(0).getLongitude();
}
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
Log.i(MyMoneyBackActivity.TAG, "Position : " + latitude + " " + longitude);
point = new LatLng(latitude, longitude);
// Add a new marker for this shop
drawMarker(map, point, rec, "");
}
map.setInfoWindowAdapter(new PopupAdapter(this,
getLayoutInflater(),
images));
//point = new LatLng(CAMERA_LAT, CAMERA_LNG);
//drawMarker(map, point, null, "Centro");
// Display last reading information
if(mBestReading!=null){
onLocationChanged(mBestReading);
}
if (MyMoneyBackActivity.progressDialog.isShowing()) {
MyMoneyBackActivity.progressDialog.dismiss();
MyMoneyBackActivity.progressDialog = null;
}
}
But what I got for some tens of seconds is a completely black screen before the map is actually drawn.
Hardware accelartion and largeheap was the issue in my case. I removed them from the app level and used them in the activity they used.
Issue was in Manifest.
<application
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:hardwareAccelerated="false"
android:largeHeap="true">
Remove from Manifest and Use in the Activity
<activity
android:name="com.mycompayname.activities.SignUpActivity"
android:hardwareAccelerated="false"
android:largeHeap="true"/>
Check if it works in Google Play Services 6.7.76 - see here https://code.google.com/p/gmaps-api-issues/issues/detail?id=7679.

Using Maps in Android

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

Zoom in map different for city vs country android

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);

Categories

Resources