Download Google map marker icon from url using Picasso - android

I'm trying to load Google map marker icons from the web using Picasso library. I've found this way to produce it in fragment class...
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
LatLng latLng = new LatLng(26.890768, 75.753915);
Picasso.with(getActivity())
.load("image-url.png")
.resize(60, 60)
.centerCrop()
.into(new TMarker(latLng, objects.get(0)));
}
});
TMarker.class is implementation of com.squareup.picasso.Target as following...
class TMarker implements Target {
LatLng latLng;
Marker marker;
TMarker(LatLng latLng, JsonObject object) {
this.latLng = latLng;
this.marker = map.addMarker(new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_marker_default)));
this.marker.setTag(object);
}
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
marker.setIcon(BitmapDescriptorFactory.fromBitmap(bitmap));
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
I think it's the easiest approach to do this. Now the problem is, Downloaded marker image is not being displayed first time when map (fragment) is loaded. As we reload the fragment, I mean come again on this map fragment, image has been displayed every time. So it's the problem of the very first time ;)
Please provide guidelines what I've missed!

Related

Why does an image is distorted when I set it using GroundOverlay in my Google Map?

I am trying to set a screenshot of a map into another map using GroundOverlay provided by Google Maps.
First I save the bounds of the map when I take the screenshot. I get them using
borders = GoogleMap.getProjection().getVisibleRegion().latLngBounds;
After when I set the screenshot to the GroundOverlay image using that bounds, the image appears distorted. I did it like this
GroundOverlayOptions offlineMap = new GroundOverlayOptions()
.image(BitmapDescriptorFactory.fromBitmap(myBitmap))
.transparency(0)
.positionFromBounds(borders);
imageOverlay = map.addGroundOverlay(offlineMap);
Here is a screenshot of the problem:
Screenshot of the image overlay distorted
Why is happening this? How can I set the image correctly?
EDITED
I could set the image without distorsion passing the LatLng coordinates of the center of the image and the width of the image, but the thing is that the GroundOverlayOptions object needs the width in kilometers, and I calculated using the distance between the two bot points of the image in the moment that is captured.
My problem is, the image is set with correct proportions, but in the wrong place.
How can I save the attributes to set the image in the exactly same position on the map as when it was taken?
Try this code, which gets screenshot on mScreenshotButton press, than add it as overlay on mAddOverlayButton press:
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mGoogleMap;
private MapFragment mMapFragment;
private Button mAddOverlayButton;
private Button mScreenshotButton;
private Bitmap mScreenshot;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mScreenshotButton = (Button) findViewById(R.id.get_screenshot_button);
mScreenshotButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getMapScreenshot();
}
});
mAddOverlayButton = (Button) findViewById(R.id.add_overlay_button);
mAddOverlayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LatLngBounds borders = mGoogleMap.getProjection().getVisibleRegion().latLngBounds;
GroundOverlayOptions overlay = new GroundOverlayOptions()
.image(BitmapDescriptorFactory.fromBitmap(mScreenshot))
.transparency(0f)
.positionFromBounds(borders);
mGoogleMap.addGroundOverlay(overlay);
}
});
mMapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map_fragment);
mMapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
}
public void getMapScreenshot()
{
GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback() {
Bitmap bitmap;
#Override
public void onSnapshotReady(Bitmap snapshot) {
mScreenshot = snapshot;
}
};
mGoogleMap.snapshot(callback);
}
}
And there is no any distortion. Seems you didn't get borders properly.

adding a marker in image using picasso

Is it possible to add a marker on an image using any image library in android ?
so far I have loaded an image into ImageView using picasso and all the solutions I have googled involved adding marker in Google maps!
Just Like the marker center in the image
Picasso provides a generic Target interface you can use to implement your own image destination. Specifically, you will want to override onBitmapLoaded to populate your marker.
A basic implementation is given below.
public class PicassoMarker implements Target {
Marker mMarker;
PicassoMarker(Marker marker) {
mMarker = marker;
}
#Override
public int hashCode() {
return mMarker.hashCode();
}
#Override
public boolean equals(Object o) {
if(o instanceof PicassoMarker) {
Marker marker = ((PicassoMarker) o).mMarker;
return mMarker.equals(marker);
} else {
return false;
}
}
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
mMarker.setIcon(BitmapDescriptorFactory.fromBitmap(bitmap));
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}}
You would use it like this:
marker = new PicassoMarker(myMarker);
Picasso.with(MainActivity.this).load(URL).into(marker);

Picasso Target has been garbage collected

Good day.I have an google map with cluster manager.Simple one,where i use the cluster to draw markers grouped or not.Anyway i got an method callback from cluster manager which is the Cluster item render one.Inside that callback i am applying custom image to the marker:The user image inside marker.I found Picasso to be the best to handle bitmap loading and at the same time got me lots of headache.I am using Target class from Picasso to initiate the bitmap callbacks:OnPreLoad,OnFail,OnBitmapLoaded.The issue is that on first cluster item render the onBitmapLoaded not called and generally it is never gets called unless it has been touched second time.On first time nothing happens,no callback is triggered except OnPreLoad and by googling i found that the great Picasso holds weak reference to the class.I tried all the examples of the google:Making Target reference strong(getting the initialazation of class out of method and init the class inside my class like the follows)
#Override
protected void onClusterItemRendered(MarkerItem clusterItem, Marker marker) {
mMarker = marker;
mMarkerItem = clusterItem;
Picasso.with(mContext).load(clusterItem.getImageUrl()).transform(new CircleTransformation()).into(target);
}
private Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
Log.d(TAG, "onBitmapLoaded: ");
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
Log.d(TAG, "onBitmapFailed: ");
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
Log.d(TAG, "onPrepareLoad: ");
}
};
#Override
protected void onBeforeClusterItemRendered(MarkerItem item, MarkerOptions markerOptions) {
markerOptions.title(item.getTitle());
markerOptions.icon(item.getIcon());
}
At this point i get the same result....Sometimes the bitmap loaded and sometimes not.Mostly not...
Anyway i have tried to implement the interface class to my own class as follows:
public class PicassoMarkerView implements com.squareup.picasso.Target {
private static final String TAG = "MarkerRender";
private Bitmap mMarkerBitmap;
private ClusterManager<MarkerItem> mClusterManager;
private MarkerItem mMarkerItem;
private Marker mMarker;
public PicassoMarkerView() {
}
#Override
public int hashCode() {
return mMarker.hashCode();
}
#Override
public boolean equals(Object o) {
if (o instanceof PicassoMarkerView) {
Marker marker = ((PicassoMarkerView) o).mMarker;
return mMarker.equals(marker);
} else {
return false;
}
}
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap,
mMarkerBitmap.getWidth() - 15, (int) (mMarkerBitmap.getHeight() / 1.5 - 15),
false);
mMarker.setIcon(BitmapDescriptorFactory.fromBitmap(overlay(mMarkerBitmap, scaledBitmap, 8, 7)));
Log.d(TAG, "onBitmapLoaded: ");
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
Log.d(TAG, "onBitmapFailed: ");
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
Log.d(TAG, "onPrepareLoad: ");
}
private Bitmap overlay(Bitmap bitmap1, Bitmap bitmap2, int left, int top) {
Bitmap res = Bitmap.createBitmap(bitmap1.getWidth(), bitmap1.getHeight(),
bitmap1.getConfig());
Canvas canvas = new Canvas(res);
canvas.drawBitmap(bitmap1, new Matrix(), null);
canvas.drawBitmap(bitmap2, left, top, null);
return res;
}
public void setMarkerBitmap(Bitmap markerBitmap) {
this.mMarkerBitmap = markerBitmap;
}
public void setClusterManager(ClusterManager<MarkerItem> clusterManager) {
this.mClusterManager = clusterManager;
}
public void setMarkerItem(MarkerItem markerItem) {
this.mMarkerItem = markerItem;
}
public void setMarker(Marker marker) {
this.mMarker = marker;
}
}
Unfortunatally this is not working either...Same result...So please dear friends can you give me an working example of this?As far as i could google,the issue mostly happens to the user which try to do this inside loop and my onClusterItemRender some sort of loop lets say as it is triggered every time marker is visible to user,so yeah it is triggered several times and as fast as loop so give me some idea please and help me out...
Important to mention that i do not need to use methods from picasso like fetch(),get() as they are not necessary and not fitting the purpose of the app.
I encountered similar issue and holding reference to the target didn't help at all.
The purpose of my project was to use 2 different image downloading api's to show an images gallery and to give the user the ability to choose which api to use.
Beside Picasso I used Glide, and I was amazed by the results, Glide's api worked flawlessly in every aspect wile Picasso gave me hell (that was my first time using Glide, I usually used Picasso so far, seems like today it's gonna change ^^ ).
So my suggestion to you is:
Use glide over Picasso (no such weak reference on their target).
Since I had to use both libraries I ended up using get() in an handler, not sure if it will help you but it solved my problem:
handlerThread = new HandlerThread(HANDLER_THREAD_NAME);
handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper());
handler.post(new Runnable() {
#Override
public void run() {
Bitmap bitmap = null;
try {
bitmap = picasso.with(appContext).load(url).get();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (bitmap != null) {
//do whatever you wanna do with the picture.
//for me it was using my own cache
imageCaching.cacheImage(imageId, bitmap);
}
}
}
});

Android google map custom marker

Am using custom markers for my google map. All the marker images are getting from server and with help of lazy loading i can display . The issue is that if the maker is set before image downloading completed it never update the map with new image.
Any help would be appreciated
public class ROverViewRender extends DefaultClusterRenderer<RItem> {
private IconGenerator mIconGenerator;
private IconGenerator mClusterIconGenerator;
private RImageView mImageView;
private RImageView mImageVieStar;
private ImageView mClusterImageView;
private Context context;
private ClusterManager<RItem> mClusterManager;
private ImageLoader imageLoader;
public ROverViewRender(Context context, GoogleMap map, ClusterManager<RItem> clusterManager) {
super(context, map, clusterManager);
this.mClusterManager=clusterManager;
Activity activity = (Activity) context;
this.context=context;
mClusterIconGenerator=new IconGenerator(context);
View clustorIcon = activity.getLayoutInflater().inflate(R.layout.clustor_icon, null);
mClusterIconGenerator.setContentView(clustorIcon);
mIconGenerator=new IconGenerator(context);
View markerIcon = activity.getLayoutInflater().inflate(R.layout.marker_icon, null);
mIconGenerator.setContentView(markerIcon);
mImageView=(RImageView)markerIcon.findViewById(R.id.marker_image);
mImageVieStar=(RImageView)markerIcon.findViewById(R.id.marker_route_rating);
mClusterImageView=(NetworkImageView)clustorIcon.findViewById(R.id.cluster_image);
imageLoader=VolleySingleton.getInstance(context).getImageLoader();;
}
#Override
protected void onBeforeClusterItemRendered(final RItem item, MarkerOptions markerOptions) {
setMarkerImage(item,markerOptions);
Bitmap icon = mIconGenerator.makeIcon();
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
}
#Override
protected void onBeforeClusterRendered(Cluster<RItem> cluster, MarkerOptions markerOptions) {
Drawable drawable =context.getResources().getDrawable(R.drawable.ic_launcher);
mClusterImageView.setImageDrawable(drawable);
Bitmap icon = mClusterIconGenerator.makeIcon(String.valueOf(cluster.getSize()));
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
}
#Override
protected boolean shouldRenderAsCluster(Cluster cluster) {
// Always render clusters.
return cluster.getSize() > 1;
}
#Override
protected void onClusterItemRendered(RItem clusterItem, Marker marker) {
RLog.e("Invoked the ....>>>>>");
// setMarkerImage(clusterItem);
}
private void setMarkerImage(RItem item,final MarkerOptions markerOptions){
RLog.e("Image setter invoked..."+item.getMarkerUrl());
mImageView.setImageUrl(item.getMarkerUrl(), imageLoader);
imageLoader.get(item.getMarkerUrl(), new ImageListener() {
public void onErrorResponse(VolleyError error) {
// imageView.setImageResource(R.drawable.icon_error); // set an error image if the download fails
}
public void onResponse(ImageContainer response, boolean arg1) {
RLog.e("Image download completed...");
if (response.getBitmap() != null) {
mImageView.setImageBitmap(response.getBitmap());
}
}
});
}
}
Issue Fixed. The google map marker have setIcon method which help us to update the icon. so whenever i got the callback from image downloader i will update it through setIcon method . So far no issues ,working perfectly fine.

Refreshing makers (ClusterItems) in Google Maps v2 for Android

I'm using Google Maps Android API Utility Library and I'm downloading certain images from internet that I want to use as markers.
The way I'm doing it is like in the following snippet:
class MarkerItemClusterRenderer extends DefaultClusterRenderer<MarkerItem> {
...
#Override
protected void onBeforeClusterItemRendered(MarkerItem item,
final MarkerOptions markerOptions) {
super.onBeforeClusterItemRendered(item, markerOptions);
mImageLoader.get(item.getImageUrl(), new ImageListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("XXX", error.toString());
}
#Override
public void onResponse(ImageContainer response, boolean isImmediate) {
if (response != null && response.getBitmap() != null) {
mImageIcon.setImageBitmap(response.getBitmap());
Bitmap icon = mIconGenerator.makeIcon();
Bitmap bhalfsize = Bitmap.createScaledBitmap(icon, 150,
150, false);
markerOptions.icon(BitmapDescriptorFactory
.fromBitmap(bhalfsize));
}
}
});
}
The problem is, that when the image is downloaded, the map (and thus the marker) doesn't refresh, so most of the times (but not always) I still see the red default markers.
I tried to do mImageIcon.invalidate(); mImageIcon.requestLayout(); but there's still no luck.
Is there anyway to achieve this?
Thanks a lot in advance.
You just need to make all this stuff in
protected void onClusterItemRendered(T clusterItem, Marker marker) {
...
}
In onBeforeClusterItemRendered you set icon on MarkerOptions in async callback. At this time it could be added to map and become real Marker. So you icon will be set to already useless object.
That's why you need to do it in onClusterItemRendered
Let's say you have GoogleMap object declared as:
private GoogleMap mMap;
In onResponse() method before applying any change to marker, try writing following statement to clear previous markers:
mMap.clear();
Now set your new marker.
I might be a bit late but i write it down so it can be useful for somebody looking for a solution like i was.
Basically what you have to do is refresh the marker and not the ClusterItem, but i used my own ClusterItem implementation to store some important data.
So your code inside onBeforeClusterItemRendered becomes like this:
LatLngBounds bounds = map.getProjection().getVisibleRegion().latLngBounds; //take visible region on map
if(bounds.contains(item.getPosition()) && !item.hasImage()) { //if item is not inside that region or it has an image already don't load his image
mImageLoader.get(item.getImageUrl(), new ImageListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("XXX", error.toString());
}
#Override
public void onResponse(ImageContainer response, boolean isImmediate) {
if (response != null && response.getBitmap() != null) {
mImageIcon.setImageBitmap(response.getBitmap());
Bitmap icon = mIconGenerator.makeIcon();
Bitmap bhalfsize = Bitmap.createScaledBitmap(icon, 150,
150, false);
//Set has image flag
item.setHasImage(true);
//Find the right marker
MarkerManager.Collection markerCollection = mClusterManager.getMarkerCollection();
Collection<Marker> markers = markerCollection.getMarkers();
for (Marker m : markers) {
if (id.equals(m.getTitle())) {
//set the icon
m.setIcon(BitmapDescriptorFactory.fromBitmap(image));
break;
}
}
}
}
});
}
And your MyItem class must have some parameters which are useful for remember our stuff:
public class MyItem implements ClusterItem {
private String itemId;
private LatLng mPosition;
private WMWall wall;
private boolean hasImage = false;
public MyItem(double latitude, double longitude) {
mPosition = new LatLng(latitude, longitude);
}
#Override
public LatLng getPosition() {
return mPosition;
}
public WMWall getWall() {
return wall;
}
public void setWall(WMWall wall) {
this.wall = wall;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public boolean hasImage() {
return hasImage;
}
public void setHasImage(boolean hasImage) {
this.hasImage = hasImage;
}
}
It is really important to load only the images of markers contained into bounds, otherwise you'll run into OOM.
And if the hasImage() method returns true we don't need to load the image again since it is already stored into the marker object.

Categories

Resources