我正在Android项目中使用Kotlin。 MapView是片段。
当用户选择多边形时,我会更改其笔触颜色。问题是有时onPolygonClick方法检测到不同的多边形。您可以在此GIF中看到它:https://gyazo.com/167aed90529031df01c07d7f583f790e
onPolygonClick方法:
override fun onPolygonClick(polygon: Polygon?) {
polygons.forEach {
it.strokeColor = Color.BLACK
}
polygon?.strokeColor = Color.WHITE
}
首先,我从服务器获取六边形,然后将其绘制在地图上。这是在将数据提取到向地图添加多边形:
之后调用的方法private fun drawRegion(regions: Array<Kraj>) {
//reset map
googleMap.clear()
polygons = ArrayList()
setMapViewBounds(regions)
for (region in regions) {
val rnd = Random()
val color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256))
for (hexagon in region.hexagons) {
val options = PolygonOptions()
for (point in hexagon) {
options.add(point)
}
options.strokeColor(Color.BLACK)
options.fillColor(color)
options.strokeWidth(2.5.toFloat())
options.clickable(true)
val pol = googleMap.addPolygon(options)
pol.tag = region.id
polygons.add(pol)
}
}
}
如您所见,我还将所有多边形保存到多边形数组,以便可以在onPolygonClick方法中访问所有它们。
onMapReady方法:
override fun onMapReady(map: GoogleMap?) {
map?.let {
googleMap = it
googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
activity?.applicationContext, R.raw.empty_map_style
)
)
}
map?.setOnMapClickListener(this)
map?.setOnPolygonClickListener(this)
addObservers()
}
我不知道为什么MapView检测到不同的多边形,但是我做了一个解决方法。
如果您遇到与我相同的问题,只需将可点击的多边形选项设置为false(否则,如果您点击多边形,onMapClick将不起作用,请设置onMapClickListener并检测单击了哪个多边形:
override fun onMapClick(coords: LatLng?) {
val polygon = polygons.first {PolyUtil.containsLocation(coords!!, it.points, true)}
val id = polygon?.tag.let { it } as Int
polygons.forEach {
it.strokeColor = Color.BLACK
val itId = it?.tag.let { it } as Int
if (it == polygon) {
it.strokeColor = Color.BLUE
}
}
viewModel.userClickedOnPolygonWithId(id)
polygon?.strokeColor = Color.WHITE
}