Now got problem that I cannot fetch and display custom icon into Google Maps from URL. Regarding Google's example, only icon to be displayed into Google map. But what I want to know is to display icon from URL.
private Marker melbourne = mMap.addMarker(new MarkerOptions()
.position(MELBOURNE)
.title("Melbourne")
.snippet("Population: 4,137,400")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)));
and here is my coding.
if(c != null){
if(c.moveToFirst()){
do {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(Double.parseDouble(c.getString(2)), Double.parseDouble(c.getString(3))))
.title(c.getString(0))
.icon(BitmapDescriptorFactory.fromBitmap(bmp))
.snippet(c.getString(1)));
} while(c.moveToNext());
}
}
You can download Bitmap as
Bitmap bmp = BitmapFactory.decodeStream(myurl.openConnection().getInputStream());
Used a thread to get the bitmap
Then
.icon(BitmapDescriptorFactory.fromBitmap(bmp)));
From your comments you get NetworkOnMainThreadException
So use a thread.
Thread thread = new Thread(new Runnable(){
@Override
public void run(){
URL url ;
try {
url = new URL("myurl");
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
source = mMap.addMarker(new MarkerOptions()
.position(sc)
.title("MyHome")
.snippet("Bangalore")
.icon(BitmapDescriptorFactory.fromResource(bmp)));
}
});
}
});
thread.start();
You can't update ui from a background thread. use runOnUiThread
.
Using asycntask
Make your asycn taks an inner class of your activity. Declare Bitmap as a class variable.
class TheTask extends AsyncTask <Void,Void,Void>
{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
URL url ;
try {
url = new URL("myurl");
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
source = mMap.addMarker(new MarkerOptions()
.position(sc)
.title("MyHome")
.snippet("Bangalore")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin)));
}
}
I used Ion to load an image. it is a very good library.
to set marker icon from url is very simple.
try {
Bitmap bmImg = Ion.with(context)
.load("http://example.com").asBitmap().get();
mMap.addMarker(new MarkerOptions().position(latlng)
.icon(BitmapDescriptorFactory.fromBitmap(bmImg)));
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
hope this help
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With