Hi I am using Async task to grab longitude and latitude in an JSONArray. I am able to draw polyline but I cannot figure out how to draw put in the start and the end of the polyline.
// Initialization
ArrayList<LatLng> polylines = new ArrayList<LatLng>();
JSONArray lines = null;
JSONObject jsonPolyline;
LatLng polyline;
And here is what I have on the onPostExecute of my AsyncTask
lines = json.getJSONArray("track");
for (int i = 0; i < lines.length(); i++) {
jsonPolyline = lines.getJSONObject(i);
polyline = new LatLng(Double.valueOf(jsonPolyline.getString("lat")),
Double.valueOf(jsonPolyline.getString("lon")));
polylines.add(polyline);
}
/*call the polyline */
myMap.addPolyline(new PolylineOptions().addAll(polylines).width(2.0f).color(Color.GREEN));
I tried using , ListIterator but since my Arraylist is <latlng> , I cannot get the first and last element on the arraylist.
How can I get the first and last element on my arraylist so that I can draw marker on the start and end position.
Every Java List<> implements get() and size() methods:
first = polylines.get(0);
last = polylines.get(polyline.size() -1);
Related
in my application i get 25 markers from the webservice, and i add them to the map, then when user move the map i detect the center position and i get new 25 markers to add them in the map. the process must be:
1-get 25 markers from webservice
2-add the 25 markers to the map
3-when map move, detect the center position
4-get new 25 markers
5-add the new 25 markers to the map
6-delete the old 25 markers from the map
my problem is in number 6, how can i delete the 25 old markers after adding the 25 new markers.
i hope that i can find any helpful ideas, and thank you
#Barns thank you for your help, that loop doesn't work and i get this error java.util.HashMap$HashIterator.nextEntry, so i change it with this loop and finnaly it works
for (Iterator<Map.Entry<String, Marker>> iterator = markerList.entrySet().iterator(); iterator.hasNext();){
Map.Entry<String, Marker> entry = iterator.next();
//Log.e("key", entry.getKey()+"");
String bikeId = entry.getKey();
int i = SearchBike(bikeId);
//Log.e("i",i+"");
if (i == 0) {
Marker marker = entry.getValue();
marker.remove();
iterator.remove();
markerList.remove(bikeId);
}
}
for SearchBike(bikeId) i create it because i can't use arrayList.contain() because the result is an object not a string
private int SearchBike(String id){
int i = 0;
for (Bikes bike : arrayList){
if (bike.getId().equals(id)) {
i++;
}
}
return i;
}
so if i==0 that's mean the marker doesn't exist in the new list and should be deleted from the map
Create a HashMap class variable to hold information about the markers:
HashMap<Long, Marker> markerList = new HashMap<>();
(I assume bike.getId() returns a long type, but if you have used a different type you must change the definition of the HashMap and the following code to reflect that type.)
After the for (Bikes bike : arrayList) loop is run go through all the values in the markerList and remove the Markers that aren't in the arrayList.
private void addMarkers(){
//set Markers of bikes list
//First loop!!
for (Bikes bike : arrayList){
BitmapDescriptor pinMarker = null;
LatLng latLng = new LatLng(Double.parseDouble(bike.getLatitude()),Double.parseDouble(bike.getLongitude()));
switch (bike.getBreakdown()){
case "false":
pinMarker = pinWork;
break;
case "true":
pinMarker = pinMaintenance;
break;
}
Marker marker = VelosMap.addMarker(new MarkerOptions()
.position(latLng)
.icon(pinMarker)
.zIndex(1));
if(!markerList.containsKey(bike.getId())){
Marker marker = map.addMarker(marker);
//Add the marker to the marker list
markerList.put(bike.getId(), marker);
HashMap<String,String>data=new HashMap<String,String>();
data.put("id",bike.getId());
data.put("imei",bike.getImei());
data.put("inUse",bike.getInUse());
data.put("breakdown",bike.getBreakdown());
marker.setTag(data);
}
}
// This will iterate through all the items in the new list ...
//...and remove the markers that are not found in the new list
// Second Loop!!
Iterator<Long> it = markerList.keySet().iterator();
while(it.hasNext();){
Long key = it.next();
if(!bikeContains(key)){
Marker marker = markerList.remove(key);
marker.remove();
}
}
}
private boolean bikeContains(Long id){
for (Bikes bike : arrayList){
Long bikeId = bike.getId();
if(bikeId == id){
return true;
}
}
return false;
}
EXPLANATION:
The first time through addMarkers():
The markerList is empty so in line if(!markerList.containsKey(bike.getId())){ a new entry will be added every pass through the first loop for (Bikes bike : arrayList){. And the Marker will be added to the map. In the second loop for (Long key : markerList.keySet()){ we iterate through the HashMap and if the arrayList does not contain the "key" then it is removed from the markerList and from the map. But, because this is the first time through, nothing will be removed.
The second time through the addMarkers() method different bike locations are present in the arrayList containing the Bike data which should have bikes with different "id" values than the first time around--at least for some bikes.
This time when if(!markerList.containsKey(bike.getId())){ is called some of the values for bike.getId() will still be in the markerList --> nothing is done! But, some bike.getId() values will not be in the list--> these will be add to the list and markers added to the map. This means you will have more than 25 markers and more than 25 elements in markerList.
In the second loop for (Long key : markerList.keySet()){ a check is performed to see if the arrayList contains the keys from the markerList. If not in arrayList then that marker is removed from the markerList and the from the map.
What you must do is, before adding the new markers, you must clear the map by calling mGoogleMap.clear() . And you have to do this every time before adding the new markers.
I'm currently developing an android google maps app help to get direction between 2 points on the map. I'm able to get the response from google maps service (Direction API) and draw polyline (Google Maps Android SDK) base on list of steps but the line is not snap to the road (curved line stick to road on the map), it's just straight line.
How can I draw polyline snap to road in Android app? I'm using Android Studio.
Here is my code to draw polyline.
void updateMapDirection() {
Polyline newPolyline;
PolylineOptions options = new PolylineOptions().width(3).color(Color.BLUE).geodesic(true);
LatLng latLng = new LatLng(mLegs.get(0).getmStartLocation().getmLatitude(),
mLegs.get(0).getmStartLocation().getmLongitude());
options.add(latLng);
for (WNStep i : mLegs.get(0).getmSteps()) {
latLng = new LatLng(i.getmEndLocation().getmLatitude(), i.getmEndLocation().getmLongitude());
options.add(latLng);
}
newPolyline = map.addPolyline(options);
}
Thanks for your help.
This is how you can do it:
Once you have your JSON object as "result". Parse it, Also decode the polyline in form of a List.
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes
.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);
Finally add Polyline Option by looping over the list and setting the properties of your polyline corresponding to the road you want to show as retrieved from Direction API on Google Maps.
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int z = 0; z < list.size(); z++) {
LatLng point = list.get(z);
options.add(point);
}
line = myMap.addPolyline(options);
In an android application I want to check if a targetMarker is among the friendMarkers and if it is, then change that one friendMarker to the targetMarker, thus I don't have to remove the friendMarker and add the targetMarker. My question is how do I do this?
First, I need to convert the optionMarker array into a Marker array.
Second, I need to check the Id-s
Third, I need to transform the friendMarker into a targetMarker
MainActivity - I activate the method in the actionbar: (the storeMarker is not fully functioning, tries to store the optionMarker array in a Marker array - unsuccessfully.
if (id == R.id.get_target) {
// this is for getting the random target - and placing a marker on the Map
targetClass = randomTarget.getRandomTarget();
targetMarker = googleMap.addMarker(targetClass.marker);
// here I get the friendMarkers
MarkerOptions[] markers = randomTarget.getMarkers();
Marker [] array;
// the rest of the code is my try to convert the optionMarker array into Marker array
for (int j = 0; j < markers.length; j++){
// array[j] = storeMarkers().getId();
}
if (targetMarker.getId() == storeMarkers().getId()) {
}
}
And this is from the Target class - the optionMarker array
// puts the online player's location into an array of markeroptions
public MarkerOptions [] getMarkers() {
playerFunctions = new PlayerFunctions();
JSONArray array = playerFunctions.getAllOnline();
try {
MarkerOptions[] markers = new MarkerOptions[array.length()];
for(int i = 0; i < array.length(); i++) {
JSONObject element = array.getJSONObject(i);
markers[i] = new MarkerOptions()
.position(new LatLng(Double.parseDouble((String)element.get("lat")), Double.parseDouble((String)element.get("long"))))
.title((String)element.get("name"));
}
return markers;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
Thanks for the replies.
I need to add a given number of markers to a map using a for loop. The Log messages tell me the function to add each marker is called, but only one marker (two at most) are displayed on the map. My two functions are the following:
private void paintInMap(String description){
map.clear(); // to erase previous markers
String[] zones = getResources().getStringArray(R.array.zonas); // array of place names
String[] coord = getResources().getStringArray(R.array.coordinates); // array of place coordinates (placed in the same order)
String[] route = description.split(", "); // split the different places of the route description
for(int i=0; i<route.length; i++){
for(int j=0; j<zones.length; j++{
if(route[i].equals(zones[j])){
LatLng latLng = getCoordinates(coord[j]); // call function to get coordinates from String
placeMarker(latLng, zones[j]);
}
}
}
}
and:
private void placeMarker(LatLng coordinates, String name){
map.addMarker(new MarkerOptions()
.title(name)
.icon(BitMapDescriptorFactory.fromResource(R.drawable.gpsmap))
.position(coordinates)
.flat(true)
.rotation(90));
Log.d("PLACE", name+" added to map");
}
Apparently my code is correct, but on runtime it only displays one (or two) markers. I have checked the Log messages and the function is being called, but the markers do no appear. Moreover, one of the markers appears in an unspecified location (which corresponds to the first value of the coordinates array by the way)
Is this a runtime bug in Eclipse? How can I solve this?
map.clear(); // to erase previous markers
new AsyncTask<String, MarkerOptions, Void>() {
private void placeMarker(LatLng coordinates, String name) {
publishProgress(new MarkerOptions()
.title(name)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.gpsmap))
.position(coordinates)
.flat(true)
.rotation(90));
Log.d("PLACE", name + " added to map");
}
#Override
protected Void doInBackground(String... params) {
String[] zones = getResources().getStringArray(R.array.zonas); // array of place names
String[] coord = getResources().getStringArray(R.array.coordinates); // array of place coordinates (placed in the same order)
String[] route = params[0].split(", "); // split the different places of the route description
for (int i=0; i<route.length; i++) {
for (int j=0; j<zones.length; j++) {
if (route[i].equals(zones[j])) {
LatLng latLng = getCoordinates(coord[j]); // call function to get coordinates from String
placeMarker(latLng, zones[j]);
}
}
}
return null;
}
#Override
protected void onProgressUpdate(MarkerOptions... markers) {
map.addMarker(markers[0]);
}
}.execute(description);
I finally solved it by running the for loop in the UI thread instead of doing it using an AsyncTask
......
route = descriptionRoute.split(", ");
coordinates = getCoordinates(coord);
String[] zonas = getResources().getStringArray(R.array.array_zonas_madrid);
String[] coord = getResources().getStringArray(R.array.array_coordinates);
for(int i=0; i<route.length; i++){
for(int j=0; j<zonas.length; j++){
if(route[i].equals(zonas[j])){
LatLng latLng = getCoordinates(coord[j]);
placeMarker(latLng, zonas[j]);
}
}
}
....
i am currently trying to implement an ActionBar-Button that on usage sets all my markers on my GoogleMap-object visible or invisible. My problem is that i don't know how i can get a reference to all my markers once they have been created and are shown on my map. Im looking for a solution where i stash all my marker-objects into an array, that i can access in other parts of my code aswell. is this approach reasonable?
here is what i am thinking of:
private Marker[] mMarkerArray = null;
for (int i = 0; i < MainActivity.customers.size(); i++) {
LatLng location = new LatLng(mData.lat, mData.lng);
Marker marker = mMap.addMarker(new MarkerOptions().position(location)
.title(mData.title)
.snippet(mData.snippet));
mMarkerArray.add(marker);
}
and set all my markers invisible on within another method:
for (int i = 0; i < mMarkerArray.length;; i++) {
mMarkerArray[i].setVisible(false);
}
it refuses to add the markers to a Marker[]-array. how can i achieve it?
mMarkerArray.add(marker) doesnt work
i figured out an answer that also regards my customerList having customers without coordinates --> (0,0;0,0). inspired by this blog.
initialize ArrayList:
private ArrayList<Marker> mMarkerArray = new ArrayList<Marker>();
add marker to my map and to the mMarkerArray:
for (int i = 0; i < MainActivity.customers.size(); i++) {
Customer customer = MainActivity.customers.get(i);
if (customer.getLon() != 0.0) {
if (!customer.isProspect()) {
Data mData= new Data(customer.getLat(),customer.getLon(),customer.getName(),
customer.getOrt());
LatLng location = new LatLng(mData.lat, mData.lng);
Marker marker = mMap.addMarker(new MarkerOptions().position(location)
.title(mData.title)
.snippet(mData.snippet));
mMarkerArray.add(marker);
}}}
set all markers not-visible
for (Marker marker : mMarkerArray) {
marker.setVisible(false);
//marker.remove(); <-- works too!
}
Replace
private Marker[] mMarkerArray = null;
with
private List<Marker> mMarkerArray = new ArrayList<Marker>();
and you should be fine.
If you use Android Maps Extensions, you can simply iterate over all markers using
for (Marker marker : googleMap.getMarkers()) {
marker.setVisible(false);
}
without having your own List of all Markers.
You can keep a Collection of OverlayItem within your Activity or Fragment and then call MapView.getOverlays().clear() to make them "invisible" and then add them back to make them visible again. Call MapView.invalidate() after each action to cause the map to be repainted.