将 MKLocalSearch 限制在一个区域
Limit MKLocalSearch to a region
我正在使用 MKLocalSearch 搜索地点并将结果显示在地图上。
问题是有时如果一家餐馆存在于另一个州,例如,它会去另一个州,我想将结果限制在我所在的地区。
这是我的代码
let searchRadius: CLLocationDistance = 10000
let region = MKCoordinateRegionMakeWithDistance(location.coordinate, searchRadius * 2.0, searchRadius * 2.0)
map.setRegion(region, animated: true)
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = getRandomPlace()
request.region = map.region
let search = MKLocalSearch(request: request)
search.start { response, error in
guard let response = response else {
print("There was an error searching for: \(request.naturalLanguageQuery) error: \(error)")
return
}
for item in response.mapItems {
self.dropPinZoomIn(item.placemark)
}
}
您无法阻止响应包含跨越某些人为边界的结果。您已经为您的请求定义了 region
,结果将有利于该地区。但即便如此,docs 还是很清楚的:
Specifying a region does not guarantee that the results will all be inside the region. It is merely a hint to the search engine.
所以,你得到的就是你得到的。您不能阻止服务器返回它 returns.
的结果
如果您那么想要运行通过返回的response
地图项并且不为其中一些是因为您不喜欢它们所在的位置,这完全取决于您。但是你的代码不会那样做;您只是在盲目地为其中 所有 个标记。
简单的解决方案
for item in res.mapItems {
let n1 = item.placemark.coordinate.latitude - 0.2
let n2 = item.placemark.coordinate.latitude + 0.2
let n3 = item.placemark.coordinate.longitude - 0.2
let n4 = item.placemark.coordinate.longitude + 0.2
if n1...n2 ~= self.region2.center.latitude && n3...n4 ~= self.region2.center.longitude {
print("Number is inside the range")
self.locations.append(LandModel(placemark: item.placemark, distance: 0.0))
}
}
我正在使用 MKLocalSearch 搜索地点并将结果显示在地图上。 问题是有时如果一家餐馆存在于另一个州,例如,它会去另一个州,我想将结果限制在我所在的地区。 这是我的代码
let searchRadius: CLLocationDistance = 10000
let region = MKCoordinateRegionMakeWithDistance(location.coordinate, searchRadius * 2.0, searchRadius * 2.0)
map.setRegion(region, animated: true)
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = getRandomPlace()
request.region = map.region
let search = MKLocalSearch(request: request)
search.start { response, error in
guard let response = response else {
print("There was an error searching for: \(request.naturalLanguageQuery) error: \(error)")
return
}
for item in response.mapItems {
self.dropPinZoomIn(item.placemark)
}
}
您无法阻止响应包含跨越某些人为边界的结果。您已经为您的请求定义了 region
,结果将有利于该地区。但即便如此,docs 还是很清楚的:
Specifying a region does not guarantee that the results will all be inside the region. It is merely a hint to the search engine.
所以,你得到的就是你得到的。您不能阻止服务器返回它 returns.
的结果如果您那么想要运行通过返回的response
地图项并且不为其中一些是因为您不喜欢它们所在的位置,这完全取决于您。但是你的代码不会那样做;您只是在盲目地为其中 所有 个标记。
简单的解决方案
for item in res.mapItems {
let n1 = item.placemark.coordinate.latitude - 0.2
let n2 = item.placemark.coordinate.latitude + 0.2
let n3 = item.placemark.coordinate.longitude - 0.2
let n4 = item.placemark.coordinate.longitude + 0.2
if n1...n2 ~= self.region2.center.latitude && n3...n4 ~= self.region2.center.longitude {
print("Number is inside the range")
self.locations.append(LandModel(placemark: item.placemark, distance: 0.0))
}
}