Okay, so I am developing a google maps like application using android studio. And right now I am having difficulty in understanding it. So my problem is I cannot set a specific destination that I want to go to and then draw a polyline going to it. Can somebody please help me. Thanks in advance
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
}
});
Related
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 trying to replace mMpap.SetMyPosition(true); function with my own. I had some success on it and when my custom image for "My Position Icon" is tapped, it moves camera to current location with my custom marker.
Everything works fine on it except whenever "My Position Icon" is tapped, it leaves a copy of marker to that position and moves to current location with a new marker.
I am fairly new to Android Development and looking for some help.
My code inside onCreate(Bundle savedInstanceState) is:
ImageView img = (ImageView) findViewById(R.id.myPostionButton);
img.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getTheLocation();
}
});
And getTheLocation() is:
if (location != null) {
final double latitude = location.getLatitude();
final double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
final Marker marker = mMap.addMarker(
new MarkerOptions()
.position(new LatLng(latitude, longitude))
.draggable(true)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_marker)));
mMap.setTrafficEnabled(true);
mMap.setMinZoomPreference(10.0f);
mMap.setMaxZoomPreference(20.0f);
//mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16.0f),4000 , null);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16.0f));
mMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
#Override
public void onCameraMove() {
LatLng centerOfMap = mMap.getCameraPosition().target;
marker.setPosition(centerOfMap);
}
});
mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
LatLng centerOfMap = mMap.getCameraPosition().target;
marker.setPosition(centerOfMap);
double latitude = centerOfMap.latitude;
double longitude = centerOfMap.longitude;
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
String str = addressList.get(0).getAddressLine(0) + ", ";
str += addressList.get(0).getSubLocality() + ", ";
str += addressList.get(0).getLocality() + ", ";
str += addressList.get(0).getCountryCode();
mFromAddress.setText(str);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
And onMapReady(GoogleMap googleMap) is:
mMap = googleMap;
getTheLocation();
Please Help.
You can try any one of the following based on your situation:
1. If you have only one marker in map, before adding the new marker, clear the map using mMap.clear();
2. If you have multiple markers then you have to keep your current marker object as member variable mMarker. Then just before adding the new marker you can use mMarker.remove();.
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.
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));