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.
Related
Google Map not showing in marshmallow device when build an app at API level greater than 23 but it showing correctly below marshmallow version.I have used MapView.
Actally i am getting Current lat lang (0,0) in Marshmallow that's why i am facing issue in marshmallow.For getting current lat lang i am using this line:-
private void getCurrentLatLong() {
try {
gps = new GPSTracker(getActivity());
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
System.out.println("latitude print==" + latitude);
lat = String.valueOf(latitude);
lng = String.valueOf(longitude);
System.out.println("lat long check====" + "lati :" + lat + " -- lng :" + lng);
if (lat.equalsIgnoreCase("0.0") || lng.equalsIgnoreCase("0.0")) {
getCurrentLatLong();
} else {
mMapView.onResume();
setMap();
}
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
Grant app permissions first, Setting -> Your App -> Permission -> enabled require permission
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();
What I want to do is just show driving routes to my Fragment Map when the Marker is Clicked.
This Tutorial is my source.
Right now the route only shows on OTHER app not in the myactivity layout. What I want to do is show the driving direction route in my fragment
Here is my MainActivity.Class
public class MainActivity extends ActionBarActivity implements GoogleMap.OnMarkerClickListener {
private LatLng Mark_Kantor_Gubernur = new LatLng(-0.9376155, 100.3600001);
private LatLng Mark_Bappeda_prov_Sumbar = new LatLng(-0.913884, 100.359176);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting Map From Google
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
googleMap = supportMapFragment.getMap();
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.setTrafficEnabled(true);
//Getting Location Based on Fused Location(GPS & Network)
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
//Handle map when opened on first time
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(13));
//Setting UP Marker
googleMap.addMarker(new MarkerOptions().position(Mark_Kantor_Gubernur)
.title("Kantor Gubernur")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_cp)));
googleMap.addMarker(new MarkerOptions().position(Mark_Bappeda_prov_Sumbar)
.title("Kantor Bappeda SUMBAR")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.marker_cp)));
TextView locationTV = (TextView) findViewById(R.id.tvLatLongLocation);
locationTV.setText("Latitude:" + latitude + ",Longitude:" + longitude);
//Setting onclick marker & Direction to Marker
googleMap.setOnMarkerClickListener(this);
}
#Override
public boolean onMarkerClick(Marker marker) {
//you can handle marker click from here
try {
StringBuilder stringBuilder = new StringBuilder();
String daddr = (String.valueOf(marker.getPosition().latitude)+","+String.valueOf(marker.getPosition().longitude));
stringBuilder.append("http://maps.google.com/maps?f=d&hl=en");
stringBuilder.append("&saddr="+String.valueOf(googleMap.getMyLocation().getLatitude())+","
+String.valueOf(googleMap.getMyLocation().getLongitude()));
stringBuilder.append("&daddr="+daddr);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(stringBuilder.toString()));
startActivity(intent);
}catch (Exception ee)
{
Toast.makeText(getApplicationContext(), "Lokasi Saat Ini Belum Didapatkan, Coba Nyalakan GPS, Keluar Ruangan dan Tunggu Beberapa Saat", Toast.LENGTH_LONG).show();
}
return false;
}
I have looked at J2ME/Android/BlackBerry - Driving directions, Route Between Two Locations, Draw Route On Google Map but this is showing just straight lines between the users location and destination, what I want is driving route.
If I add this polyline code:
Polyline polyline = googleMap.addPolyline(new PolylineOptions().add(new LatLng(googleMap.getMyLocation().getLatitude(), googleMap.getMyLocation().getLongitude()),new LatLng(marker.getPosition().latitude, marker.getPosition().longitude)).width(2).color(Color.RED).geodesic(true));
It just shows straight lines in a Google map fragment
Note: Please include comments and an explanation on answer code, I'm very new in android and still learning.
Selector elements should be placed in res\drawable. Right click on 'drawable', select 'new' then select 'Drawable resource file'. Name the file and you should be good to go.
How to update a position of my marker in Google Maps v2 in android without adding a new one?
Every time my location changes i have to update the position of the user in a Google Map, but it always creating a new point e the map, how to avoid this behaviour?
Here is how im updating
public void onLocationChanged(Location location) {
this.localizacao = location;
loc = location;
if (mAdapter.getCount() == 0){
getAdvsFromServer();
}
LatLng me = new LatLng(location.getLatitude(), location.getLongitude());
if (eu != null){
Log.d("marker_eu", "removed");
eu.remove();
}
eu = map.addMarker(new MarkerOptions().position(me).title("Eu"));
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_maps_indicator_current_position);
eu.setIcon(BitmapDescriptorFactory.fromBitmap(bm));
map.moveCamera(CameraUpdateFactory.newLatLng(me));
//map.moveCamera(CameraUpdateFactory.newLatLngZoom(me, 13));
}
UPDATE:
This way it always creating a new point too:
public void onLocationChanged(Location location) {
this.localizacao = location;
loc = location;
if (mAdapter.getCount() == 0){
getAdvsFromServer();
}
if (ac != null){
ac.setLayoutLocalizacaoVisible(View.GONE, View.VISIBLE);
}
LatLng me = new LatLng(location.getLatitude(), location.getLongitude());
// if (eu != null){
// Log.d("marker_eu", "removed");
// eu.remove();
// }
if (eu == null){
eu = map.addMarker(new MarkerOptions().position(me).title("Eu"));
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_maps_indicator_current_position);
eu.setIcon(BitmapDescriptorFactory.fromBitmap(bm));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(me, 13));
}else {
eu.setPosition(me);
map.moveCamera(CameraUpdateFactory.newLatLng(me));
}
You should not add new marker every time location change, instead you can directly set the new position into your existing marker.
For example:
marker.setPosition(new LatLng(lat, lng));
If your activity is creating a new Marker while running this method, than eu is somehow cleared or null going into the if statement. eu.setPosition(me);would not create another Marker but simply change the location of the marker without altering any other attributes.
If you are certain that the new marker is not created somewhere else in your code then check the state of eu before going into your if statement and find out why it is null at that point by backtracking. Check the position of the Marker to verify the location after the execution. Use the following and watch the logcat.
System.out.println(eu);
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);