I'm trying out the Google API V2 Heatmap (Android) which was introduced this february and it's not working entirely. I'm not sure if it's the same problem as Google Maps API v2 HeatMap Won't Reliably Display (and I can't contact him by comments because I don't have enough rep.. :c ).
Using locations from file
Anyway, what I was trying to do was an App with just a GoogleMap and the same locations as in their guide (https://developers.google.com/maps/documentation/android/utility/heatmap) and when I launch it, I can only see 3/5 locations.
I tried adding more points and still, it's consistently not showing them all, but I can't see a pattern or something. The code is the same as in their guide.
private void addHeatMap() {
List<LatLng> list = null;
// Get the data: latitude/longitude positions of police stations.
try {
list = readItems(R.raw.police_stations);
} catch (JSONException e) {
Toast.makeText(this, "Problem reading list of locations.", Toast.LENGTH_LONG).show();
}
// Create a heat map tile provider, passing it the latlngs of the police stations.
mProvider = new HeatmapTileProvider.Builder()
.data(list)
.build();
// Add a tile overlay to the map, using the heat map tile provider.
mOverlay = mMap.addTileOverlay(new TileOverlayOptions().tileProvider(mProvider));
}
private ArrayList<LatLng> readItems(int resource) throws JSONException {
ArrayList<LatLng> list = new ArrayList<LatLng>();
InputStream inputStream = getResources().openRawResource(resource);
String json = new Scanner(inputStream).useDelimiter("\\A").next();
JSONArray array = new JSONArray(json);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
double lat = object.getDouble("lat");
double lng = object.getDouble("lng");
LatLng latLng = new LatLng(lat, lng);
list.add(latLng);
}
return list;
}
Trying with weighted locations had the same result, some of them showing and some not.
Using locations "onClick"
In this case, normal LatLng were added and the map was updated until I got to the equator and then it stopped :p.
For the case of weightedLatLngs, it didn't update/show any :(
That's basically it... I don't know where to look for more information, whether it's something with the API, the device or something else.
Does anyone know why this might happen and/or where to look for a solution ?
Thank you in advance !
Btw, I'm using Android 4.0.4 on a Samsung Galaxy S Duos if that may prove useful..
The Googlemaps API for Heatmap only allows for 1,000 plotted points. You can reduced that by filtering out your original data or by converting to "weighted locations".
This looks like it was caused by this bug, where bounds calculations were excluding max values.
This is now fixed.
Related
I'm using this library to show a kml markers in a map in Android Maps V2.
I´m trying to get the lat and lon from a kml layer to do zoom directly to a placemark after add it to a map.
I tried to do this:
layer = new KmlLayer(mMap,R.raw.ruta, this );
layer.addLayerToMap();
for (KmlPlacemark act : layer.getPlacemarks()){
System.out.println("hi");//not iterate
}
but it doesn´t enter in the loop I read this kml-feature but don't work as is
You will have to read the 1st container of the KML-layer before attempting to read information about the placemarks:
KmlContainer = layer.getContainers().iterator().next();
if (kmlContainer == null) return;
for (KmlPlacemarks placemark : kmlContainer.getPlacemarks()) {
// Do the placemark magic here!
}
I am trying to use groundoverlay on Google Maps just to see if I can get an image on Google Maps. I have no error and looking through the documentation and examples. The image does not display.
Here is part of my code where I am implementing groundoverlay:
private GroundOverlay mGroundOverlay;
private static final LatLng NEWARK = new LatLng(40.714086, -74.228697);
.....
Under
protected void onCreate(Bundle savedInstanceState) {
.....
public void setImage(){
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(NEWARK, 11));
mGroundOverlay = googleMap.addGroundOverlay(new GroundOverlayOptions()
.image(BitmapDescriptorFactory.fromResource(R.drawable.battery)).anchor(0, 1)
.position(NEWARK , 85000f,6500f));
}
I have the image "battery.jpeg" in my resource folder, drawable-hpdi
Can some look at my code and tell me what I am missing? Since I am a beginner in Android I would like an explanation as well.
Maybe I'm reading your intention incorrectly, but if you are trying to use the Android Maps API, you'll have to get a key from the API dashboard; the irreplaceable vogella has a tutorial:
http://www.vogella.com/tutorials/AndroidGoogleMaps/article.html
if you are a new droidgrammer, I can think of no better programmer to learn from.
also, could you post your logcat? FYI: you can use Logcat Extreme on a rooted device to get live logging overlaid on your device that you can also send to file... it's the bee's knees and pouring over logcat readouts will accelerate your education greatly. =]
gl hf
Check this one
LatLng c1 = new LatLng( -33.67032801,151.30209310);
LatLng c2 = new LatLng( -33.66687426,151.30269820);
LatLng c3 = new LatLng( -33.66657936,151.30026840);
LatLng c4 = new LatLng( -33.67003309,151.29966320);
LatLngBounds latLngBounds = new LatLngBounds(c1, c3).including(c2).including(c4);
GroundOverlayOptions groundOverlayOptions = new
GroundOverlayOptions();
BitmapDescriptor bitmapDescriptor =
BitmapDescriptorFactory.fromAsset("h1.png");
groundOverlayOptions.image(bitmapDescriptor);
groundOverlayOptions.positionFromBounds(latLngBounds);
map.addGroundOverlay(groundOverlayOptions);
I am doing android app for field drawing and now I am making share function. Is there are any way to pass field coordinates from mobile to maps.google.com, make link, and send this link for example to friend via sms or email, that he just need to push the link and my drawed field will show up to him in browser? Is there any tool to do this or I need to create some web app for this?
Try out it
// To draw boundray on map
private void drawPolygon() {
polygonOptions = new PolygonOptions(); // consider new options
setStrokeWidth();
for (LatLng latLng : drawCoordinates) {
Marker marker = googleMap.addMarker(new MarkerOptions().position(latLng).title(latLng.toString()));
marker.setVisible(false);
polygonOptions.add(marker.getPosition()).strokeColor(Color.RED);
polygonOptions.fillColor(Color.TRANSPARENT);
polygonOptions.visible(true);
}
List<LatLng> points = polygonOptions.getPoints();
if (!points.isEmpty()) {
polygon = googleMap.addPolygon(polygonOptions);
Log.i("Poly lines","Successfully added polyline on map");
}
}
This question already has answers here:
Get driving directions using Google Maps API v2
(4 answers)
Closed 3 years ago.
I was looking for an answer using Google and here, and the only relevant posts I have found are:
Google Maps Android V2 and Direction API
Get driving directions using Google Maps API v2
but there is no answer there. So I have already mentioned it but I will say that again. I am looking for a solution for the Google Map API v2 using FragmentActivity and a SupportMagFragment and LatLng objects and not using MapView ,MapActivity and GeoPoint.
In addition I don't have the Overlay object to use so I can't paint the direction on the map, is there an alternative for that?
So is there a way to do that?
Try this solution here. You can get driving or walking direction on V2.
The Overlay is indeed something to forget.
Polylines can easily be drawn
https://developers.google.com/maps/documentation/android/lines#add_a_polyline
Just loop through yourr points after you parsed tjhe JSON response:
PolylineOptions rectOptions = new PolylineOptions()
.add(new LatLng(37.35, -122.0))
.add(new LatLng(37.45, -122.0)) // North of the previous point, but at the same longitude
.add(new LatLng(37.45, -122.2)) // Same latitude, and 30km to the west
.add(new LatLng(37.35, -122.2)) // Same longitude, and 16km to the south
.add(new LatLng(37.35, -122.0)); // Closes the polyline.
// Set the rectangle's color to red
rectOptions.color(Color.RED);
// Get back the mutable Polyline
Polyline polyline = myMap.addPolyline(rectOptions);
Your question title is much more general than your requirements, so I will answer this in a way that I think will benefit those viewing this question and hopefully meet your requirements in perhaps a different way.
If you are not showing directions in the context of a map already being a loaded fragment and something having been done to show directions over the map (which is probably similar to what the OP is doing), it's easier and I believe standard to do this with an Intent.
This launches a map pathing activity (through a separate application - where the app launched depends on the user's compatible apps, which by default is Google Maps) that plots directions from the origin address (String originAddress) to the
destination address (String destinationAddress) via roadways:
// Build the URI query string.
String uriPath = "https://www.google.com/maps/dir/";
// Format parameters according to documentation at:
// https://developers.google.com/maps/documentation/directions/intro
String uriParams =
"?api=1" +
"&origin=" + originAddress.replace(" ", "+")
.replace(",", "") +
"&destination=" + destinationAddress.replace(" ", "+")
.replace(",", "") +
"&travelmode=driving";
Uri queryURI = Uri.parse(uriPath + uriParams);
// Open the map.
Intent intent = new Intent(Intent.ACTION_VIEW, queryURI);
startActivity(activity, intent, null);
(Where activity is simply the currently active Activity - obtained through whatever means are appropriate in the current programming context).
The following code gets an address String from a LatLng object (which must then be processed for the URI query String as above):
/**
* Retrieves an address `String` from a `LatLng` object.
*/
private void getAddressFromLocation(
final StringBuilder address, final LatLng latlng) {
// Create the URI query String.
String uriPath =
"https://maps.googleapis.com/maps/api/geocode/json";
String uriParams =
"?latlng=" + String.format("%f,%f",
latlng.latitude, latlng.longitude) +
"&key=" + GOOGLE_MAPS_WEB_API_KEY;
String uriString = uriPath + uriParams;
// Issue the query using the Volley library for networking.
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JSONObject response = null;
// Required for JsonObjectRequest, but not important here.
Map<String, String> jsonParams = new HashMap<String, String>();
JsonObjectRequest request =
new JsonObjectRequest(Request.Method.POST,
uriString,
new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (response != null) {
String resultString =
response.getJSONArray("results")
.getJSONObject(0)
.getString("formatted_address");
// Assumes `address` was empty.
address.append(resultString);
} // end of if
// No response was received.
} catch (JSONException e) {
// Most likely, an assumption about the JSON
// structure was invalid.
e.printStackTrace();
}
} // end of `onResponse()`
}, // end of `new Response.Listener<JSONObject>()`
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(LOG_TAG, "Error occurred ", error);
}
});
// Add the request to the request queue.
// `VolleyRequestQueue` is a singleton containing
// an instance of a Volley `RequestQueue`.
VolleyRequestQueue.getInstance(activity)
.addToRequestQueue(request);
}
This request is asynchronous, but it can be made synchronous.
You will need to call toString() on the actual parameter passed to address to obtain originAddress.
Q:I was looking for an answer using Google and here, and the only
relevant posts i have found are: Google Maps Android V2 and Direction
API Google map API v2 - get driving directions
Answer: Your saying, "but there is no answer there." is not absolutely right. In this site, you can find just only a few clues about that. I think you will not get the perfect code and concrete implement KNOW-HOWs here. In fact, many developers want to make the app to display the routing or directions on Google Maps. But I think there is no solution to get directions just only with the pure Google Maps API v2.
Q: So I have already mentioned it but I will say that again. I am
looking for a solution for the Google Map API v2 using
FragmentActivity and a SupportMagFragment and LatLng objects and not
using MapView ,MapActivtiy and GeoPoint.
Answer: Here are a few good sample tutorials (click here). You can find what you want.
Q: In addition i don't have the Overlay object to use so i can't paint
the direction on the map, is there an alternative for that? So is
there a way to do that?
Answer: In the Google Maps API v2, the annoying Overlay and so on are not any more required. For this, you can find the answer in my linked site above.
I have an Android application and I'm trying to populate a Google Map with a route, this route is store on a JSON array this way:
JSONArray.getString("points") = ["-33.45591917507404, -70.59198361376951","-33.453484420618416, -70.61635952929686"]
So in this case I have
Point A=(-33.49088437162095, -70.64043194102163) and
Point B=(-33.49423964397045, -70.63992768572683)
And my route or path is A-----B
I'm new to Android and I was wondering how to get this to work. Also, in this case my route is A-----B, but it can also be A----B----C----D. I can have any number of points on the path.
One thing you can try is the Google Maps Polyline object: https://developers.google.com/maps/documentation/javascript/reference#Polyline You specify to setPath() an ordered list of the points (either an Array of LatLng or an MVCArray or LatLng), you want to connect together on the map, and Google Maps will make a polyline for you to your specifications.
// path = Array of LatLng or MVCArray of LatLng
routeLine = new Polyline();
routeLine.setPath(JSONArray);
In your case, passing JSONArray into setPath should work OK.
If you want to get fancy and incorporate directions, you need to use the Google Directions API. https://developers.google.com/maps/documentation/javascript/directions
// All waypoints must be stopovers for the Directions service to optimize their route.
// start & end are of type String or LatLng, waypts is an array of String or LatLng
request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: [type Boolean],
travelMode: [type TravelMode]
};
// go on and actually perform the request
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
// if successful, this will run
}
});
Once you finish constructing your object, you should be able to display it by running setMap(map:Map), such as
routeLine.setMap(map)