How to generate marker array in Kotlin - android

I have 2 separate location data and I need to make array of them (I guess I need to make array of them, maybe you have better idea!) in order to add marker for both locations in google map.
Code
Locations part are commented
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
// Try to obtain the map from the SupportMapFragment.
if (ContextCompat.checkSelfPermission(
requireContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION
) ==
PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(
requireContext(),
android.Manifest.permission.ACCESS_COARSE_LOCATION
) ==
PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
Toast.makeText(context, "Allow location access", Toast.LENGTH_LONG).show();
}
mFusedLocationClient = context?.let { LocationServices.getFusedLocationProviderClient(it) }!!
mFusedLocationClient.lastLocation
.addOnSuccessListener { location: Location? ->
if (location != null) {
// Location 1 (current location of user)
val driverLatLng = LatLng(location.latitude, location.longitude)
mMap!!.moveCamera(CameraUpdateFactory.newLatLngZoom(driverLatLng, 15f))
// Zoom in, animating the camera.
mMap!!.animateCamera(CameraUpdateFactory.zoomIn())
}
}
//new
// Location 2
val geoCoder = Geocoder(context)
var address = geoCoder.getFromLocationName(customerAddressArgument, 1)!![0]
val customerLatLng= LatLng(address.latitude, address.longitude)
mMap!!.addMarker(MarkerOptions().position(customerLatLng).title("Customer Location"))
val cameraPosition = CameraPosition.Builder()
.target(customerLatLng) // Sets the center of the map to Mountain View
.zoom(17f) // Sets the zoom
.bearing(90f) // Sets the orientation of the camera to east
.tilt(30f) // Sets the tilt of the camera to 30 degrees
.build() // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
}
What I need is to make array of: val driverLatLng = LatLng(location.latitude, location.longitude) and val customerLatLng = LatLng(address.latitude, address.longitude)
Any idea?

Here is the solution for adding marker to map
first get both location point like location2 and location2
val markerOptions = MarkerOptions()
// First marker
markerOptions.position(location1).icon(BitmapDescriptorFactory.fromBitmap
(BitmapFactory.decodeResource(resources, R.mipmap.ic_user_location)))
mMap.addMarker(markerOptions)
// second marker
markerOptions.position(location2).icon(BitmapDescriptorFactory.fromBitmap
(BitmapFactory.decodeResource(resources, R.mipmap.ic_user_location)))
mMap.addMarker(markerOptions)
// Move camera
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
// resize icon
private fun resizeIcon():Bitmap{
val height = 120
val width = 60
val b: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.ic_map_marker)
val smallMarker = Bitmap.createScaledBitmap(b, width, height, false)
return smallMarker
}

Create
var markerList:ArrayList<Marker> = ArrayList()
Create your marker
val marker = MarkerOptions().position(latlng).anchor(
0.5f,
0.5f
).title(your tittle).snippet(it.event_id).icon(your marker icon)
//Than add markers into marker list
markerList.add(marker)
use for loop to set the marker into google map
markerList.forEach{
// set marker to your google map with it
}

Related

Get current location button is not show on the jetpack compose google map

I want to show the current location button (isMyLocationButtonEnabled) on the Google Map but it's not showing.
How can I display the get current location button?
AndroidView(
factory = { mapView }
) {
mapView.getMapAsync { map ->
map.apply {
navigatorViewModel.apply {
viewModelScope.launch {
isMapEditable.collectLatest {
uiSettings.setAllGesturesEnabled(
it,
)
uiSettings.isMyLocationButtonEnabled = true
}
}
val location = lastSelectedLocation.value
val position = LatLng(location.latitude, location.longitude)
moveCamera(
CameraUpdateFactory.newLatLngZoom(
position,
Constants.ZOOM_CAMERA
)
)
setOnCameraIdleListener {
val cameraPosition = map.cameraPosition
updateLocation(
cameraPosition.target.latitude,
cameraPosition.target.longitude
)
}
}
}
}
}
Add these properties:
val uiSettings = remember {
MapUiSettings(myLocationButtonEnabled = true)
}
val properties by remember {
mutableStateOf(MapProperties(isMyLocationEnabled = true))
}
GoogleMap:
GoogleMap(
modifier = modifier.fillMaxSize(),
cameraPositionState = cameraPositionState,
properties = properties,
uiSettings = uiSettings)
I'm replying so late, this answer might help someone else!
To show MyLocationButton in google map you need enable both
map.isMyLocationEnabled = true & uiSettings.isMyLocationButtonEnabled = true

How to zoom into a location in google map in kotlin?

This's on map ready function. I want to zoom into that location. but using this only can get marker not zoom.
override fun onMapReady(googleMap: GoogleMap?) {
mMap = googleMap!!
val sydney = LatLng(-34.0, 151.0)
mMap.addMarker(MarkerOptions().position(sydney).title("Sydney"))
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}
Try this to zoom onto the user location
> private void showArea(LatLng latLng) {
> CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(AppConstant.MAP_DEFAULT_ZOOM).build();
> mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
> }

How to show current location in HMS map with custom marker option?

I have used HMS Map in my app. I am select some location using location kit search and displaying in map with custom marker. I can able to get Latitude and Longitude perfectly. Also i can display the selected location in map too before few days. But currently unable to show. I did not change anything in code. So what should be problem?
private fun setMapWithCurrentLoc(lastLocation: android.location.Location?) {
if (lastLocation != null) {
val location = LatLng(lastLocation.latitude, lastLocation.longitude)
if (map != null) {
map!!.clear()
map!!.addCircle(
CircleOptions()
.radius(500.0)
.center(location)
.clickable(false)
.fillColor(ContextCompat.getColor(requireContext(), R.color.purple_trans))
.strokeColor(ContextCompat.getColor(requireContext(), R.color.transparent))
.strokeWidth(1f)
)
map!!.addMarker(
MarkerOptions()
.position(location)
.icon(
BitmapDescriptorFactory.fromBitmap(
Utils.createCustomMarker(
requireContext(),
childUrl!!
)
)
)
.draggable(true)
)
map!!.animateCamera(
CameraUpdateFactory.newLatLngZoom(
LatLng(location.latitude, location.longitude),
currentZoomSetting.toFloat()
)
)
}
}
}
Try to change some of your code and test in a Activity with com.huawei.hms.maps.SupportMapFragment, it works okey:
override fun onMapReady(paramHuaweiMap: HuaweiMap?) {
Log.i(TAG, "onMapReady: ")
hMap = paramHuaweiMap
hMap!!.isMyLocationEnabled = true
setMapWithCurrentLoc(LatLng(48.893478, 2.334595))
}
private fun setMapWithCurrentLoc(location: LatLng) {
var map = hMap
if (map != null) {
map!!.clear()
map!!.addCircle(
CircleOptions()
.radius(500.0)
.center(location)
.clickable(false)
.fillColor(ContextCompat.getColor(this, R.color.colorAccent))
.strokeColor(ContextCompat.getColor(this, R.color.colorAccent))
.strokeWidth(1f)
)
map!!.addMarker(
MarkerOptions()
.position(location)
.icon(
BitmapDescriptorFactory.fromResource(
R.mipmap.ic_launcher
)
)
.draggable(true)
)
map!!.animateCamera(
CameraUpdateFactory.newLatLngZoom(
LatLng(location.latitude, location.longitude),
11f
)
)
}
}
implementation 'com.huawei.hms:maps:6.0.0.301'
could test this in your code to see if works.

Map not clickable around marker in Google Map SDK for Android

I am building some app like image below, I want to force markers not to be clickable, but there is no setClickable(false) for Marker or MarkerOptions.
Currently area around marker (see attachment) is not clickable ( click is passed to marker, not map)
You have to use Overlay instead of marker in the Map to get exactly what you desire. You could follow this link, similar is done in JavaScript here.
I found a way to manually handle clicks for markers.
Add a touchable wrapper as described in this stackoverflow answer: https://stackoverflow.com/a/58039285/1499750
Add a gesture detector to your fragment and listen to single taps, then find the closest marker based on lat lng:
private var gestureDetector: GestureDetector? = null
...
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
gestureDetector = GestureDetector(context, GoogleMapsGestureListener { e -> onMapSingleTap(e) })
//id of touchable wrapper - can use findViewById here instead if not using kotlin synthetics
googleMapsTouchableWrapper?.onTouch = {
gestureDetector?.onTouchEvent(it)
}
}
private fun onMapSingleTap(e: MotionEvent) {
val latLng = map?.projection?.fromScreenLocation(Point(e.x.toInt(), e.y.toInt())) ?: return
//this assumes you are maintaining a set of the latlngs for your markers
val closestNearbyLatLng = markerLatLngs?.findClosestNearbyLatLng(latLng)
//assuming you have a map of latlng to marker you can now find that marker based on latlng and do whatever you need to with it
}
private fun Set<LatLng>.findClosestNearbyLatLng(latLng: LatLng): LatLng? {
val map = map ?: return null
val screenDistance = map.projection.visibleRegion.latLngBounds.northeast.distanceBetweenInKm(map.projection.visibleRegion.latLngBounds.southwest)
val closestLatLng = this.minBy { latLng.distanceBetweenInKm(it) } ?: return null
if (latLng.distanceBetweenInKm(closestLatLng) < screenDistance/40) {
return closestLatLng
}
return null
}
fun LatLong.distanceBetweenInKm(latLng: LatLng): Double {
if (this == latLng) {
return 0.0
}
val earthRadius = 6371.0 //km value;
//converting to radians
val latPoint1Radians = Math.toRadians(latitude)
val lngPoint1Radians = Math.toRadians(longitude)
val latPoint2Radians = Math.toRadians(latLng.latitude)
val lngPoint2Radians = Math.toRadians(latLng.longitude)
var distance = sin((latPoint2Radians - latPoint1Radians) / 2.0).pow(2.0) + (cos(latPoint1Radians) * cos(latPoint2Radians)
* sin((lngPoint2Radians - lngPoint1Radians) / 2.0).pow(2.0))
distance = 2.0 * earthRadius * asin(sqrt(distance))
return abs(distance) //km value
}
class GoogleMapsGestureListener(private val onSingleTap: (MotionEvent) -> Unit) : GestureDetector.SimpleOnGestureListener() {
override fun onSingleTapConfirmed(e: MotionEvent?): Boolean {
super.onSingleTapConfirmed(e)
e?.let { onSingleTap(it) }
return true
}
}
I recently was able to create a formula to create an area surrounding a certain position on a Google Map, that is also scalable with zoom level.
Here I converted the LatLng coordinates from the marker to actual coordinates on the phone:
//array that holds all locations of every marker
//after a marker is created add the position in here
val positionList = mutableListOf<LatLng>()
//map is variable type GoogleMap
map.setOnMapClickListener {
var inRange = false
for(i in positionList.indices) {
//establish corners of boundaries surrounding markers
val points = positionList.toCoordinates(map)
//check if clicked position falls in one of the positions' bounds
val isInRangeLng = (points[i][2]..points[i][3]).contains(it.longitude)
val isInRangeLat = (points[i][0]..points[i][1]).contains(it.latitude)
//if click lands in of the positions' bounds, stop loop and return inRange
//true
if(isInRangeLat && isInRangeLng) {
inRange = true
break
}
}
if(!inRange) {
//APPLY YOUR LOGIC IF CLICK WAS NOT IN AREA
} else {
//APPLY YOUR LOGIC IF CLICK WAS IN AREA
}
}
//Extension function used to simplify logic
/** Convert LatLng to coordinates on phone **/
fun List<LatLng>.toCoordinates(map: GoogleMap): List<List<Double>> {
val proj: Projection = map.projection
val coordinateList = mutableListOf<List<Double>>()
//create bounds for each position in list
this.forEach {
//get screen coordinates at the current LatLng
val point = proj.toScreenLocation(it)
val left = point.x - 100
val right = point.x + 100
val top = point.y - 100
val bottom = point.y + 100
//convert bounds into two points diagonal of each other
val topRight = Point(right, top)
val bottomLeft = Point(left, bottom)
//convert the two points into LatLng points and get the bounds in north,
//south, west, and east
val northEast = proj.fromScreenLocation(topRight)
val north = northEast.latitude
val east = northEast.longitude
val southWest = proj.fromScreenLocation(bottomLeft)
val south = southWest.latitude
val west = southWest.longitude
//add the bounds to be returned in a list which corresponds to a certain
//position
coordinateList.add(listOf(
south,
north,
west,
east
))
}
return coordinateList
}
This can be used for a lot more than markers too.

Change cluster manager's item icon programmatically

On my map I use the Marker Cluster Utility to group the markers. All the markers when first put on the map have the same icon, then, when I move close to one of the markers, its icon must change. I've read other discussions about this, but as far as I've understood, I'd need to remove the marker and generate it again with the new icon.
My markers belong to a cluster, so I should remove the marker from the cluster, generate a new marker and add it to the cluster manager object.
The problem is that the cluster manager object has a renderer attached to it which also defines the marker's icon and it would use the same icon as for the removed marker.
Some code:
the renderer class
class VenueMarkerRender(private val context: Context, map: GoogleMap, clusterManager: ClusterManager<Venue>)
: DefaultClusterRenderer<Venue>(context, map, clusterManager) {
override fun onBeforeClusterItemRendered(item: Venue?, markerOptions: MarkerOptions?) {
super.onBeforeClusterItemRendered(item, markerOptions)
markerOptions!!.icon(bitmapDescriptorFromVector(context, R.drawable.ic_map_black))
}
override fun onBeforeClusterRendered(cluster: Cluster<Venue>?, markerOptions: MarkerOptions?) {
super.onBeforeClusterRendered(cluster, markerOptions)
markerOptions!!.icon(bitmapDescriptorFromVector(context, R.drawable.ic_home_black_24dp))
}
override fun shouldRenderAsCluster(cluster: Cluster<Venue>?): Boolean {
return cluster!!.size > 1
}
/**
* Takes a vector image and make it available to use as a marker's icon
*/
private fun bitmapDescriptorFromVector(context: Context, #DrawableRes vectorDrawableResourceId: Int): BitmapDescriptor {
// ...
return BitmapDescriptorFactory.fromBitmap(bitmap)
}
}
the Venue class
class Venue : ClusterItem {
private var mPosition: LatLng
private var mTitle: String? = null
private var mSnippet: String? = null
constructor(lat: Double, lng: Double, title: String, snippet: String) {
mPosition = LatLng(lat, lng)
mTitle = title
mSnippet = snippet
}
override fun getPosition(): LatLng {
return mPosition
}
override fun getTitle(): String {
return mTitle!!
}
override fun getSnippet(): String? {
return mSnippet
}
}
finally how the cluster manager is created and how a venue is added to it
mClusterManager = ClusterManager(this, map)
val renderer = VenueMarkerRender(this, map, mClusterManager!!)
mClusterManager!!.renderer = renderer
// other code
for (i in 0 until markers.length()) {
val marker = JSONObject(markers.getJSONObject(i).toString())
val venue = Venue(
marker.getDouble("lat"),
marker.getDouble("lng"),
marker.getString("title"),
marker.getString("snippet"),
)
mClusterManager!!.addItem(venue)
}
mClusterManager!!.cluster()
Is it possible to generate a new Venue object with its own icon and to add it to the cluster manager object? Or is there a better way to obtain what I need?
I've just found the solution, I hope this will help someone else.
I've declared the renderer as a class attribute to make it available everywhere inside the activity
private var renderer: VenueMarkerRender? = null
before it was a private variable inside the method which sets up the Cluster Manager. Then it is initialized as already shown in the previous message
renderer = VenueMarkerRender(this, map, mClusterManager!!)
Now to change the marker when I get close to it, it is enough to call this method each time that the location changes
private fun markerProximity() {
// get the venues' list from the cluster
val venues = mClusterManager!!.algorithm.items
// if the cluster was not empty
if (venues.isNotEmpty()) {
// initialize the array which will contain the distance
val distance: FloatArray = floatArrayOf(0f,0f,0f)
// loop through all the venues
for (venue:Venue in venues) {
// get the distance in meters between the current position and the venue location
Location.distanceBetween(
venue.position.latitude,
venue.position.longitude,
lastLocation.latitude,
lastLocation.longitude,
distance)
// if closer than 3 meters
if ( distance[0] < 3 ) {
// change this marker's icon
renderer!!.getMarker(venue)
.setIcon(BitmapDescriptorFactory
.fromResource(R.drawable.my_location))
}
}
}
}

Categories

Resources