下面列出了怎么用com.google.android.gms.maps.model.BitmapDescriptorFactory的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void addMarker(final Marker aMarker) {
final MarkerOptions marker = new MarkerOptions();
marker.position(new LatLng(aMarker.latitude, aMarker.longitude));
if (!TextUtils.isEmpty(aMarker.title)) {
marker.title(aMarker.title);
}
if (!TextUtils.isEmpty(aMarker.snippet)) {
marker.snippet(aMarker.snippet);
}
if (aMarker.bitmap != null) {
marker.icon(BitmapDescriptorFactory.fromBitmap(aMarker.bitmap));
} else {
if (aMarker.icon != 0) {
marker.icon(BitmapDescriptorFactory.fromResource(aMarker.icon));
}
}
if (aMarker.anchor == Marker.Anchor.CENTER) {
marker.anchor(0.5f, 0.5f);
}
mGoogleMap.addMarker(marker);
}
private void drawUserPositionMarker(Location location){
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
if(this.userPositionMarkerBitmapDescriptor == null){
userPositionMarkerBitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.user_position_point);
}
if (userPositionMarker == null) {
userPositionMarker = map.addMarker(new MarkerOptions()
.position(latLng)
.flat(true)
.anchor(0.5f, 0.5f)
.icon(this.userPositionMarkerBitmapDescriptor));
} else {
userPositionMarker.setPosition(latLng);
}
}
/**
* Highlight the marker by marker.
*/
private void highLightMarker(Marker marker) {
/*
for (Marker foundMarker : this.markers) {
if (!foundMarker.equals(marker)) {
foundMarker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
} else {
foundMarker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
foundMarker.showInfoWindow();
}
}
*/
marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
// marker.showInfoWindow();
//marker.remove();
//Utils.bounceMarker(googleMap, marker);
this.selectedMarker = marker;
}
@Override
protected void onPostExecute(Void aVoid) {
if (status == ConnectionResult.SUCCESS) {
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title(venueAddress);
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
} else {
DialogFragment dialogFragment = new PlayServicesUnavailableDialogFragment();
dialogFragment.show(getActivity().getFragmentManager(), "Play Service Problem");
}
}
/**
* Creates a {@link BitmapDescriptor} from a drawable.
* This is particularly useful for {@link GoogleMap} {@link Marker}s.
*
* @param drawable The drawable that should be a {@link BitmapDescriptor}.
* @return The created {@link BitmapDescriptor}.
*/
@NonNull
public static BitmapDescriptor getBitmapDescriptorFromDrawable(@NonNull Drawable drawable) {
BitmapDescriptor bitmapDescriptor;
// Usually the pin could be loaded via BitmapDescriptorFactory directly.
// The target map_pin is a VectorDrawable which is currently not supported
// within BitmapDescriptors.
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
drawable.setBounds(0, 0, width, height);
Bitmap markerBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(markerBitmap);
drawable.draw(canvas);
bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(markerBitmap);
return bitmapDescriptor;
}
private void addMarkersToMap()
{
MarkerOptions options =new MarkerOptions();
options.position(BRISBANE);
options.title("brisbane");
options.snippet("Population: 2,544,634");
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
options.draggable(true);
CustomInfoWindowAdapter.brisbane=googleMap.addMarker(options);
MarkerOptions options2 =new MarkerOptions();
options2.position(ADELAIDE);
options2.title("adelaide");
options2.snippet("Population: 3,543,222");
Drawable drawable=ContextCompat.getDrawable(getApplicationContext(),R.drawable.ic_person_pin_circle_black_24dp);
options2.icon(convertDrawableToBitmap(drawable));
options2.draggable(true);
CustomInfoWindowAdapter.adelaide=googleMap.addMarker(options2);
}
private void updateMapLocation() {
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
if (mMap != null && mCurrentLocation != null) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mCurrentLocation, 5));
if (mCurrentPosMarker == null) {
mCurrentPosMarker = mMap.addMarker(new MarkerOptions().position(mCurrentLocation).icon(BitmapDescriptorFactory.fromResource(R.drawable.current_location)));
} else {
mCurrentPosMarker.setPosition(mCurrentLocation);
mCurrentPosMarker.setVisible(true);
}
}
}
});
}
private Target getTargetForPois(final Place place, final int idPlaceToGo) {
return new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
bitmap = bitmapHelper.getTintedBitmap(bitmap, ContextCompat.getColor(getContext(), R.color.orange));
bitmap = bitmapHelper.getScaledBitmap(bitmap, (int) getResources().getDimension(R.dimen._30dp));
markersMap.put(addMarkerPoi(place, BitmapDescriptorFactory.fromBitmap(bitmap), idPlaceToGo), place);
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
markersMap.put(addMarkerPoi(place, getIconPoi(), idPlaceToGo), place);
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
}
private void displayLocation(){
//add driver location
if(driverMarker!=null)driverMarker.remove();
driverMarker=mMap.addMarker(new MarkerOptions().position(new LatLng(Common.currentLat, Common.currentLng))
.title("You").icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_marker)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Common.currentLat, Common.currentLng), 14f));
geoFire.setLocation(Common.userID,
new GeoLocation(Common.currentLat, Common.currentLng),
new GeoFire.CompletionListener() {
@Override
public void onComplete(String key, DatabaseError error) {
}
});
//remove route
if(direction!=null)direction.remove();
getDirection();
}
private void requestPickup(String uid) {
DatabaseReference dbRequest=FirebaseDatabase.getInstance().getReference(Common.pickup_request_tbl);
GeoFire mGeofire=new GeoFire(dbRequest);
mGeofire.setLocation(uid, new GeoLocation(Common.currenLocation.latitude, Common.currenLocation.longitude),
new GeoFire.CompletionListener() {
@Override
public void onComplete(String key, DatabaseError error) {
}
});
if (riderMarket.isVisible())riderMarket.remove();
riderMarket=mMap.addMarker(new MarkerOptions().title(getResources().getString(R.string.pickup_here)).snippet("").position(new LatLng(Common.currenLocation.latitude, Common.currenLocation.longitude))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
riderMarket.showInfoWindow();
btnRequestPickup.setText(getResources().getString(R.string.getting_uber));
findDriver();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// Activity created for the first time.
mMarkerPosition = DEFAULT_MARKER_POSITION;
mMarkerInfo = new MarkerInfo(BitmapDescriptorFactory.HUE_RED);
mMoveCameraToMarker = true;
} else {
// Extract the state of the MapFragment:
// - Objects from the API (eg. LatLng, MarkerOptions, etc.) were stored directly in
// the savedInsanceState Bundle.
// - Custom Parcelable objects were wrapped in another Bundle.
mMarkerPosition = savedInstanceState.getParcelable(MARKER_POSITION);
Bundle bundle = savedInstanceState.getBundle(OTHER_OPTIONS);
mMarkerInfo = bundle.getParcelable(MARKER_INFO);
mMoveCameraToMarker = false;
}
getMapAsync(this);
}
/**
* Updates the waypoints.
*
* @param googleMap the google map.
*/
private void updateWaypoints(GoogleMap googleMap) {
synchronized (waypoints) {
for (Waypoint waypoint : waypoints) {
Location location = waypoint.getLocation();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
int drawableId = waypoint.getType() == WaypointType.STATISTICS
? R.drawable.ic_marker_yellow_pushpin : R.drawable.ic_marker_blue_pushpin;
MarkerOptions markerOptions = new MarkerOptions().position(latLng)
.anchor(WAYPOINT_X_ANCHOR, WAYPOINT_Y_ANCHOR).draggable(false).visible(true)
.icon(BitmapDescriptorFactory.fromResource(drawableId))
.title(String.valueOf(waypoint.getId()));
googleMap.addMarker(markerOptions);
}
}
}
private void updateMapWithNewBusLocations() {
if (startStop == null || endStop == null) {
mMap.clear();
displayStopError();
return;
}
List<Route> routesBetweenStartAndEnd = startStop.getRoutesTo(endStop);
BusManager sharedManager = BusManager.getBusManager();
for (Marker m : busesOnMap) {
m.remove();
}
busesOnMap = new ArrayList<>();
if (clickableMapMarkers == null)
clickableMapMarkers = new HashMap<>(); // New set of buses means new set of clickable markers!
for (Route r : routesBetweenStartAndEnd) {
for (Bus b : sharedManager.getBuses()) {
//if (BuildConfig.DEBUG) Log.v("BusLocations", "bus id: " + b.getID() + ", bus route: " + b.getRoute() + " vs route: " + r.getID());
if (b.getRoute().equals(r.getID())) {
Marker mMarker = mMap.addMarker(new MarkerOptions().position(b.getLocation()).icon(BitmapDescriptorFactory.fromBitmap(rotateBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_bus_arrow), b.getHeading()))).anchor(0.5f, 0.5f));
clickableMapMarkers.put(mMarker.getId(), false); // Unable to click on buses.
busesOnMap.add(mMarker);
}
}
}
}
private Marker createMarker(Entity device) {
Marker marker;
LatLng latLng = device.getLocation();
if (device.hasMdiIcon()) {
marker = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromBitmap(mifMarkerIcon.makeMaterialIcon(device.getMdiIcon())))
.position(latLng)
.zIndex(2.0f)
.anchor(mifMarkerIcon.getAnchorU(), mifMarkerIcon.getAnchorV()));
} else {
marker = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromBitmap(mifMarkerText.makeIcon(device.getFriendlyName())))
.position(latLng)
.zIndex(2.0f)
.anchor(mifMarkerText.getAnchorU(), mifMarkerText.getAnchorV()));
}
return marker;
}
private BitmapDescriptor getIcon(Date data) {
DateTime current = new DateTime(Calendar.getInstance());
DateTime last = new DateTime(data);
int diff = Minutes.minutesBetween(last, current).getMinutes();
BitmapDescriptor bitmap;
if(diff >= 5 && diff < 10 ) {
bitmap = BitmapDescriptorFactory
.fromResource(R.drawable.bus_yellow);
} else if(diff >= 10 ) {
bitmap = BitmapDescriptorFactory
.fromResource(R.drawable.bus_red);
} else {
bitmap = BitmapDescriptorFactory
.fromResource(R.drawable.bus_green);
}
return bitmap;
}
private BitmapDescriptor getBitmapDescriptorForCategory(String categoria) {
BitmapDescriptor mapIcon;
if (categoria.contains("consultório")) {
mapIcon = BitmapDescriptorFactory.fromResource(R.drawable.ic_consultorio);
} else if (categoria.contains("clínica")) {
mapIcon = BitmapDescriptorFactory.fromResource(R.drawable.ic_clinica);
} else if (categoria.contains("laboratório")) {
mapIcon = BitmapDescriptorFactory.fromResource(R.drawable.ic_laboratorio);
} else if (categoria.contains("urgência")) {
mapIcon = BitmapDescriptorFactory.fromResource(R.drawable.ic_urgente);
} else if (categoria.contains("hospital")) {
mapIcon = BitmapDescriptorFactory.fromResource(R.drawable.ic_hospital);
} else if (categoria.contains("atendimento domiciliar")) {
mapIcon = BitmapDescriptorFactory.fromResource(R.drawable.ic_domiciliar);
} else if (categoria.contains("posto de saúde")) {
mapIcon = BitmapDescriptorFactory.fromResource(R.drawable.ic_urgente);
} else if (categoria.contains("samu")) {
mapIcon = BitmapDescriptorFactory.fromResource(R.drawable.ic_samu);
} else {
mapIcon = BitmapDescriptorFactory.fromResource(R.drawable.ic_urgente);
}
return mapIcon;
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
boolean success = googleMap.setMapStyle(new MapStyleOptions(getResources()
.getString(R.string.style_json)));
if (!success) {
Log.e("Style", "Style parsing failed.");
}
LatLng jakarta = new LatLng(-6.232812, 106.820933);
LatLng southjakarta = new LatLng(-6.22865,106.8151753);
mMap.addMarker(new MarkerOptions().position(jakarta).icon(BitmapDescriptorFactory.fromBitmap(getBitmapFromView("Set Pickup Location", R.drawable.dot_pickup))));
mMap.addMarker(new MarkerOptions().position(southjakarta).icon(BitmapDescriptorFactory.fromBitmap(getBitmapFromView("Set Dropoff Location", R.drawable.dot_dropoff))));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(jakarta, 15f));
}
@Override
public void onConnected(Bundle bundle) {
if (location == null) {
// get last location device
location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (mMap != null) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));
mMap.addMarker(new MarkerOptions()
.position(new LatLng(location.getLatitude(), location.getLongitude()))
.title("Starting Point")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_marker))
);
lat = location.getLatitude();
lng = location.getLongitude();
Toast.makeText(this, "Lokasi kamu saat ini, sebagai patokan titik awal perjalanan kamu kak :')", Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onLocationChanged(Location location) {
if (location.getLatitude() != 0 || location.getLongitude() != 0) {
setFusedLatitude(location.getLatitude());
setFusedLongitude(location.getLongitude());
stopFusedLocation();
CameraPosition oldPos = googleMap.getCameraPosition();
CameraPosition pos = CameraPosition.builder(oldPos)
.target(getPosition())
.zoom(zoom)
.build();
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(pos));
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(getPosition())
.title("My Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.placeholder)));
AsyncTask placesAsync = new Places().execute(getPosition());
}
}
private void showPointerOnMap(final double latitude, final double longitude) {
mvRestaurantLocation.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_flag))
.anchor(0.0f, 1.0f)
.position(latLng));
googleMap.getUiSettings().setMyLocationButtonEnabled(false);
googleMap.getUiSettings().setZoomControlsEnabled(true);
// Updates the location and zoom of the MapView
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 15);
googleMap.moveCamera(cameraUpdate);
}
});
}
@Override
protected void onPostExecute(List<HashMap<String, String>> list) {
googleMap.clear();
for (int i = 0; i < list.size(); i++) {
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> googlePlace = list.get(i);
double lat = Double.parseDouble(googlePlace.get("lat"));
double lng = Double.parseDouble(googlePlace.get("lng"));
String placeName = googlePlace.get("place_name");
//String vicinity = googlePlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(placeName);
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.custom_marker));
googleMap.addMarker(markerOptions);
}
}
/**
* Set the icon into the marker options
*
* @param markerOptions marker options
* @param icon icon row
* @param density display density: {@link android.util.DisplayMetrics#density}
* @param iconCache icon cache
* @return true if icon was set into the marker options
*/
public static boolean setIcon(MarkerOptions markerOptions, IconRow icon, float density, IconCache iconCache) {
boolean iconSet = false;
if (icon != null) {
Bitmap iconImage = createIcon(icon, density, iconCache);
markerOptions.icon(BitmapDescriptorFactory
.fromBitmap(iconImage));
iconSet = true;
double anchorU = icon.getAnchorUOrDefault();
double anchorV = icon.getAnchorVOrDefault();
markerOptions.anchor((float) anchorU, (float) anchorV);
}
return iconSet;
}
/**
* Sets marker at given location on map
*
* @param LocationLat latitude
* @param LocationLong longitude
* @param LocationName name of location
* @param LocationIcon icon
*/
public void ShowMarker(Double LocationLat, Double LocationLong, String LocationName, Integer LocationIcon) {
LatLng Coord = new LatLng(LocationLat, LocationLong);
if (ContextCompat.checkSelfPermission(activity,
Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (map != null) {
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(Coord, 10));
MarkerOptions abc = new MarkerOptions();
MarkerOptions x = abc
.title(LocationName)
.position(Coord)
.icon(BitmapDescriptorFactory.fromResource(LocationIcon));
map.addMarker(x);
}
}
}
@Override
public void onMapReady(GoogleMap map) {
MarkerOptions markerOptions = new MarkerOptions()
.position(mMarkerPosition)
.icon(BitmapDescriptorFactory.defaultMarker(mMarkerInfo.mHue))
.draggable(true);
map.addMarker(markerOptions);
map.setOnMarkerDragListener(this);
map.setOnMarkerClickListener(this);
if (mMoveCameraToMarker) {
map.animateCamera(CameraUpdateFactory.newLatLng(mMarkerPosition));
}
}
private void moveMarker(LatLng latLng) {
if (mLocationMarker != null) {
mLocationMarker.remove();
}
mLocationMarker = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_marker_my_location))
.position(latLng).anchor(0.5f, 0.5f));
}
public void markUserPosition(Context context, LatLng posicao) {
if (userMarker != null) {
userMarker.remove();
}
userMarker = map.addMarker(new MarkerOptions()
.position(posicao)
.title(context.getString(R.string.marker_user))
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.man_maps)));
}
/**
* Add a shape marker to the map at the location. A shape marker is a transparent icon for allowing shape info windows.
*
* @param latLng lat lng location
* @param visible visible state
* @return shape marker
*/
public Marker addShapeMarker(LatLng latLng, boolean visible) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)));
markerOptions.visible(visible);
markerOptions.anchor(0.5f, 0.5f);
markerOptions.position(latLng);
Marker marker = map.addMarker(markerOptions);
return marker;
}
public RouteDrawerBuilder(GoogleMap googleMap) {
this.googleMap = googleMap;
this.pathWidth = DEFAULT_PATH_WIDTH;
this.pathColor = DEFAULT_PATH_COLOR;
this.alpha = DEFAULT_MARKER_ALPHA;
this.bitmapDescriptor = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE);
}
@SuppressLint({"RestrictedApi"})
public GglMapLocationManager(GoogleMap googleMap, Context context) {
this.mGoogleMap = googleMap;
this.context = context;
buildGoogleApiClient();
this.markerOptions = new MarkerOptions();
this.markerOptions.title("Current Position");
this.markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.location_map));
this.locationRequest = new LocationRequest();
this.locationRequest.setInterval(1000);
this.locationRequest.setFastestInterval(1000);
this.locationRequest.setPriority(100);
}
public void onLocationResult(LocationResult result) {
if (this.locationMarker != null) {
onLocationChanged(result.getLastLocation());
} else if (result.getLastLocation() != null) {
LatLng latLng = new LatLng(result.getLastLocation().getLatitude(), result.getLastLocation().getLongitude());
this.locationMarker = this.mGoogleMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.location_map)).anchor(0.5f, 0.5f));
this.mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15.555f));
}
}