I am trying to add 2 markers to the google map with the following code. It shows only one location instead of two. Can anyone look at it and comment ? I saw that the location values are distinct with a debugger.
public void updateMapWithNewLocation() {
Marker marker1 = null;
Marker marker2 = null;
LatLng latLng1 = null;
LatLng latLng2 = null;
if (mMyLocation != null) {
latLng1 = new LatLng(mMyLocation.getLatitude(), mMyLocation.getLongitude());
MarkerOptions myMarkerOptions = new MarkerOptions()
.position(latLng1)
.title("me");
marker1 = mMap.addMarker(myMarkerOptions);
}
if (mFriendLocation != null) {
latLng2 = new LatLng(mMyLocation.getLatitude(), mMyLocation.getLongitude());
MarkerOptions friendMarkerOptions = new MarkerOptions()
.position(latLng2)
.title("friend");
marker2 = mMap.addMarker(friendMarkerOptions);
}
List<Marker> markerList = new ArrayList<>();
if(marker1 != null){
markerList.add(marker1);
}
if(marker2 != null) {
markerList.add(marker2);
}
zoomToShowAllMarkers(markerList);
}
private void zoomToShowAllMarkers(List<Marker> markers) {
if ( markers == null || markers.size() < 1)
return;
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker marker : markers) {
builder.include(marker.getPosition());
}
for (Marker m : markers) {
builder.include(m.getPosition());
}
LatLngBounds bounds = builder.build();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(bounds.getCenter(), 10));
}
try using below code.
// Creating an instance of MarkerOptions
MarkerOptions markerOptions1 = new MarkerOptions();
// Setting latitude and longitude for the marker
markerOptions1.position(LatLng1);
// Adding marker on the Google Map
googleMap.addMarker(markerOptions1);
// Creating an instance of MarkerOptions
MarkerOptions markerOptions2 = new MarkerOptions();
// Setting latitude and longitude for the marker
markerOptions2.position(LatLng2);
// Adding marker on the Google Map
googleMap.addMarker(markerOptions2);
or you can add using loop inside the your custom method.
This is how I did to zoom with bounds:
map.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 20);
map.animateCamera(cameraUpdate);
}
});
The onMapLoaded() makes the zooming done after the map got loaded.
Hope this helps.
Thanks for your suggestions and looking at it.
I had a copy/paste error of using myLocation instead of friendLocation
this particular line:
latLng2 = new LatLng(mMyLocation.getLatitude() mMyLocation.getLongitude()); <-- should use mFriendLocation instead of mMyLocation.
Sorry for the trouble.
Related
Good Day! I am trying to make a tracking app where user can track the courier. But a have some troubles in some logic and codes about how can I change the marker of courier only when snapshot detect some changes in its location. Please note that the location of buyer is static(will not change even if the snapshotlistener detect changes in courier's location).
Please take a look at my codes below:
db.collection("Transactions").whereEqualTo("transactionID", transID)
.addSnapshotListener(TrackingCourierActivity.this, new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.e("DB_Error", e.toString());
} else {
for (DocumentChange dc: queryDocumentSnapshots.getDocumentChanges()){
DocumentSnapshot documentSnapshot = dc.getDocument();
TransactionsModel trasModel = documentSnapshot.toObject(TransactionsModel.class);
HashMap<String, Object> buyerData = trasModel.getBuyerData();
HashMap<String, Object> courierData = trasModel.getCourierData();
GeoPoint addressLocation = (GeoPoint) buyerData.get("buyerAddress");
GeoPoint courierLocation = (GeoPoint) courierData.get("courierLocation");
double LatitudeData = addressLocation.getLatitude();
double LongitudeData = addressLocation.getLongitude();
final LatLng latLng = new LatLng(LatitudeData, LongitudeData);
double storeLocationLatitude = courierLocation.getLatitude();
double storeLocationLongitude = courierLocation.getLongitude();
final LatLng courLatLng = new LatLng(storeLocationLatitude, storeLocationLongitude);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(latLng);
builder.include(courLatLng);
LatLngBounds bounds = builder.build();
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 200);
mMap.addMarker(pinned = new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.fromBitmap(
createCustomMarker(TrackingCourierActivity.this))).title("Your Pinned Address"));
mMap.moveCamera(cu);
Marker marker = mMap.addMarker(courier = new MarkerOptions()
.position(courLatLng)
.icon(BitmapDescriptorFactory.fromBitmap(
createCourierCustomMarker(TrackingCourierActivity.this))).title("Courier Location"));
if (dc.getType().equals(DocumentChange.Type.MODIFIED)){
marker.remove();
courier = new MarkerOptions()
.position(courLatLng)
.icon(BitmapDescriptorFactory.fromBitmap(
createCourierCustomMarker(TrackingCourierActivity.this))).title("Courier Location");
mMap.addMarker(courier);
}
}
}
}
});
Here I tried to get the locations of Both user and courier but when there's some changes in courier location, the marker wont remove and it will only duplicate it.
I have already try to achieve this type of functionality using google map direction API. You can see the picture I found this in javascript code but I want to do in android.
I want to achieve like this please click here..
PolygonOptions rectOptions2;
rectOptions2= new PolygonOptions();
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick( final LatLng latLng)
{
// PolylineOptions rectOptions = new PolylineOptions()
// .add(new LatLng(latitude, longitude));
// Polyline polyline = mMap.addPolyline(rectOptions);
// Creating a marker
BitmapDescriptor icon =
BitmapDescriptorFactory.fromResource(R.drawable.ic_map);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions .icon(icon);
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
final List<Address> listAddresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if (null != listAddresses && listAddresses.size() > 0) {
markerOptions.title(location);
location = listAddresses.get(0).getAddressLine(0);
latitude=latLng.latitude;
longitude=latLng.longitude;
}
} catch (IOException e) {
e.printStackTrace();
}
// mMap.clear();
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.addMarker(markerOptions);
lat=latitude;
lng=longitude;
rectOptions2.add(new LatLng(lat, lng));
polygon= mMap.addPolygon(rectOptions2);
polygon.setStrokeColor(Color.RED);
polygon.setFillColor(Color.BLUE);
//add lat and lng in arraylist here
}
});
I am a newbie to the android and currently working on the Google-map API.
I am able to plot multiple markers on the map but want to join multiple markers with poly line.I have referred this for the directions concern but it is for two points only.
Below is the code for the Activity:
public class MainActivity extends AppCompatActivity {
// Google Map
private GoogleMap googleMap;
// latitude and longitude
double latitude;
double longitude;
String newtime;
ArrayList<LatLng> points;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
points = new ArrayList<LatLng>();
points.add(new LatLng(21.114369, 79.049423));
points.add(new LatLng(21.113913, 79.049203));
points.add(new LatLng(21.113478, 79.048736));
points.add(new LatLng(21.113002, 79.048592));
points.add(new LatLng(21.112857, 79.047315));
points.add(new LatLng(21.112997, 79.046741));
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.setMyLocationEnabled(true);
SimpleDateFormat sdfDateTime = new SimpleDateFormat("dd-MM-yy HH:mm:ss", Locale.US);
newtime = sdfDateTime.format(new Date(System.currentTimeMillis()));
// googleMap.addMarker(marker);
drawMarker(points);
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(), "Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
}
}
}
private void drawMarker(ArrayList<LatLng> l) {
// Creating an instance of MarkerOptions
for (int i = 0; i < l.size(); i++) {
latitude = l.get(i).latitude;
longitude = l.get(i).longitude;
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Bus")
.snippet(newtime);
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// Adding marker on the Google Map
googleMap.addMarker(marker);
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(l.get(0).latitude, l.get(0).longitude)).zoom(18).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
Please help/guide me to achieve the task.
~Thanks.
Modify your drawMarker() to the following:-
private void drawMarker(ArrayList<LatLng> l) {
// Creating an instance of MarkerOptions
PolylineOptions options = new PolylineOptions();
options.color(Color.RED);
for (int i = 0; i < l.size(); i++) {
options.add(l.get(i));
MarkerOptions marker = new MarkerOptions().position(l.get(i)).title("Bus")
.snippet(newtime);
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// Adding marker on the Google Map
googleMap.addMarker(marker);
}
googleMap.addPolyline(options);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(l.get(0).latitude, l.get(0).longitude)).zoom(18).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
Here it will add lines with red color, to change colors as your wish just modify the options.color().
I use List to store marker to add to gmap and remove component it self.
List<Location> listLocation = new ArrayList<Location>();
When location updated. I were store Location to listLocation,remove the old marker . Then add the newest location to Gmap.
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
countUpdatePos++;
listLocation.add(location);
LatLng lastLocation = new LatLng(location.getLatitude(),
location.getLongitude());
gmap.moveCamera(CameraUpdateFactory.newLatLngZoom(lastLocation, 16));
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
if (addresses.size() > 0) {
int a = addresses.get(0).getMaxAddressLineIndex();
for (int i = 0; i < a; i++) {
if (i == 0) {
cityName = addresses.get(0).getAddressLine(i);
} else {
cityName = cityName + ", "
+ addresses.get(0).getAddressLine(i);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
if (countUpdatePos == 1) {
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.updated_position), 2000)
.show();
progressToLoadMap.setVisibility(View.GONE);
checkStartActivity = true;
timer = new MyCount((int) totalTime * 60 * 1000, 1000);
timer.start();
}
if (listLocation.size() > 1) {
listLocation.add(location);
// gmap.clear();
LatLng newLocation = new LatLng(location.getLatitude(),
location.getLongitude());
gmap.moveCamera(CameraUpdateFactory.newLatLngZoom(newLocation, 16));
myMarker = gmap.addMarker(new MarkerOptions().position(new LatLng(
listLocation.get(listLocation.size() - 1).getLatitude(),
listLocation.get(listLocation.size() - 1).getLongitude())));
if (myMarker != null) {
myMarker.remove();
myMarker = null;
}
gmap.addMarker(new MarkerOptions()
.title(getResources().getString(
R.string.current_location_found)).snippet(cityName)
.position(newLocation));
if (listLocation.get(listLocation.size() - 1) != null
&& listLocation.get(listLocation.size() - 1) != null) {
gmap.addPolyline(new PolylineOptions()
.add(new LatLng(listLocation.get(
listLocation.size() - 1).getLatitude(),
listLocation.get(listLocation.size() - 1)
.getLongitude()),
new LatLng(location.getLatitude(), location
.getLongitude())).width(3)
.color(Color.BLUE));
}
But when run activity, all marker still display, and no polyline add to gmap :(. Help me
here is picture
I hade the same problem and after checking my code I found that I am calling the method that add the marker twice in the oncreate and onresume events so 2 markers are added at the same position on the map so when I remove the marker using marker.remove() method one is removed but the other one remain so I thought it is not deleted. I removed the method call from the oncreate event and now it is working fine.
What you have done is correct but Just need little bit modification for Marker:
Set this globally:
Marker myMarker;
In you onCreate()
myMarker = gmap.addMarker(new MarkerOptions()
.position(new LatLng(listLocation.get(
listLocation.size() - 1).getLatitude(),
listLocation.get(listLocation.size() - 1)
.getLongitude())));
Then Whenver you want to add another Marker then Just check it out if Is there already any other marker is present. If yes then remove it if you want.
For that:
if(myMarker!=null)
{
marker.remove();
marker = null;
}
myMarker = gmap.addMarker(new MarkerOptions()
.title(getResources().getString(
R.string.current_location_found)).snippet(cityName)
.position(newLocation));
For Polyline you might check if lat,long are not null.
I've seen something like this before.
try making
//put this at the top of your class
Marker myMarker;
//this is using the reference
myMarker = gmap.addMarker(new MarkerOptions()
.title(getResources().getString(
R.string.current_location_found)).snippet(cityName)
.position(newLocation));
myMarker.remove();
an instance variable. WHen you call remove() it needs to be the same marker that you added.
make sure you keep a reference to the marker :
myMarker = gmap.addMarker(new MarkerOptions()
.title(getResources().getString(
R.string.current_location_found)).snippet(cityName)
.position(newLocation));
if (listLocation.get(listLocation.size() - 1) != null
&& listLocation.get(listLocation.size() - 1) != null) {
gmap.addPolyline(new PolylineOptions()
.add(new LatLng(listLocation.get(
listLocation.size() - 1).getLatitude(),
listLocation.get(listLocation.size() - 1)
.getLongitude()),
new LatLng(location.getLatitude(), location
.getLongitude())).width(3)
.color(Color.BLUE));
I tried to draw a polyline between given markers, which are saved at an arraylist (poisMap). Based on my research I created the following code. I get no error and also no line, but the markers are all visible.
How have I to place the polyline method in order to get it working?
private void setUpMap() {
for (int i = 0; i < poisMap.size(); i++) {
latitude = poisMap.get(i).getLatitudePoi();
if (latitude == 0) {
Log.i("debug", "latitude null");
}
longitude = poisMap.get(i).getLongitudePoi();
poiTitle = poisMap.get(i).getTitle();
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(poiTitle));
PolylineOptions routeDraw = new PolylineOptions().add(new LatLng(latitude,longitude)).width(5).color(Color.BLUE);
Polyline polyline = mMap.addPolyline(routeDraw);
}
latitudeZoom = poisMap.get(0).getLatitudePoi();
longitudeZoom = poisMap.get(0).getLongitudePoi();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitudeZoom,longitudeZoom),14));
mMap.setMyLocationEnabled(true);
}
private void setUpMap() {
PolylineOptions routeDraw = new PolylineOptions().width(5).color(Color.BLUE);
for (int i = 0; i < poisMap.size(); i++) {
latitude = poisMap.get(i).getLatitudePoi();
if (latitude == 0) {
Log.i("debug", "latitude null");
}
longitude = poisMap.get(i).getLongitudePoi();
poiTitle = poisMap.get(i).getTitle();
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(poiTitle));
routeDraw.add(new LatLng(latitude,longitude))
}
Polyline polyline = mMap.addPolyline(routeDraw);
latitudeZoom = poisMap.get(0).getLatitudePoi();
longitudeZoom = poisMap.get(0).getLongitudePoi();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitudeZoom,longitudeZoom),14));
mMap.setMyLocationEnabled(true);
}
other
private void setUpMap() {
LatLng[] latlngarray = new LatLng[poisMap.size()];
for (int i = 0; i < poisMap.size(); i++) {
latitude = poisMap.get(i).getLatitudePoi();
if (latitude == 0) {
Log.i("debug", "latitude null");
}
longitude = poisMap.get(i).getLongitudePoi();
poiTitle = poisMap.get(i).getTitle();
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(poiTitle));
latlngarray[i]= new LatLng(latitude, longitude);
}
PolylineOptions routeDraw = new PolylineOptions().add(latlngarray).width(5).color(Color.BLUE);
Polyline polyline = mMap.addPolyline(routeDraw);
latitudeZoom = poisMap.get(0).getLatitudePoi();
longitudeZoom = poisMap.get(0).getLongitudePoi();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitudeZoom,longitudeZoom),14));
mMap.setMyLocationEnabled(true);
}
check this it is helpfull if you use google map
[http://wptrafficanalyzer.in/blog/drawing-driving-route-directions-between-two-locations-using-google-directions-in-google-map-android-api-v2/][1]