使用 google 地图获取附近的地点
Fetching nearby places using google maps
我正在尝试使用 google 地图来查找我当前位置附近的地点。
我在 Google Developer Console 中创建了一个项目并获得了 'ios APIkey' 和 'Server APIkey'。我还为 iOS 启用了 Google Places API 和 Google Maps SDK。
下面是查找附近地点的代码。
func fetchPlacesNearCoordinate(coordinate: CLLocationCoordinate2D, radius: Double, name : String){
var urlString = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=\(apiServerKey)&location=\(coordinate.latitude),\(coordinate.longitude)&radius=\(radius)&rankby=prominence&sensor=true"
urlString += "&name=\(name)"
urlString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
println(urlString)
if placesTask.taskIdentifier > 0 && placesTask.state == .Running {
placesTask.cancel()
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
placesTask = session.dataTaskWithURL(NSURL(string: urlString)!) {data, response, error in
println("inside.")
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if let json = NSJSONSerialization.JSONObjectWithData(data, options:nil, error:nil) as? NSDictionary {
if let results = json["results"] as? NSArray {
for rawPlace:AnyObject in results {
println(rawPlace)
self.results.append(rawPlace as! String)
}
}
}
self.placesTask.resume()
}
}
传递的坐标是当前位置的坐标。如果我执行上面的代码,什么也没有发生,但是生成的 url 是有效的。如果我把 url 放在 Google 中,我会得到正确的结果。但我的应用程序中没有显示任何内容。请帮我解决这个问题。请让我知道哪里错了!!!
您已将地点添加到结果数组,但您已执行任何操作来更新您的地图视图,例如,将标记添加到您的地图视图。
示例代码向地图视图添加标记:
let returnedPlaces: NSArray? = jsonResult["results"] as? NSArray
if returnedPlaces != nil {
for index in 0..<returnedPlaces!.count {
if let returnedPlace = returnedPlaces?[index] as? NSDictionary {
var placeName = ""
var latitude = 0.0
var longitude = 0.0
if let name = returnedPlace["name"] as? NSString {
placeName = name as String
}
if let geometry = returnedPlace["geometry"] as? NSDictionary {
if let location = geometry["location"] as? NSDictionary {
if let lat = location["lat"] as? Double {
latitude = lat
}
if let lng = location["lng"] as? Double {
longitude = lng
}
}
}
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(latitude, longitude)
marker.title = placeName
marker.map = self.mapView
}
}
}
您可以在 Swift 中查看 this tutorial 如何使用 Google 地图前往附近的地点。
只需设置您的 Latt、long 和 GoogleAPIKey。
NSString *urlString= [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=%@,%@&radius=2000&key=%@",lati,longi,kGoogleAPIKey];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (connectionError)
{
NSLog(@"Error");
}
else
{
NSDictionary *dictJson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSArray *arrayPlaces = [[NSArray alloc] initWithArray:[dictJson objectForKey:@"results"]];
NSLog("Place %@",arrayPlaces);
}
}];
此外,如果您想通过文本搜索地点,只需将 urlString 如下所示。
NSString *urlString = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/autocomplete/json?sensor=true&key=%@&language=en&input=%@&query=123+main+street&radius=50000&location=0.0,0.0&rankby=distance",kGoogleAPIKey,searchText];
在 arrayPlaces 中你有附近的地方。
我正在尝试使用 google 地图来查找我当前位置附近的地点。 我在 Google Developer Console 中创建了一个项目并获得了 'ios APIkey' 和 'Server APIkey'。我还为 iOS 启用了 Google Places API 和 Google Maps SDK。 下面是查找附近地点的代码。
func fetchPlacesNearCoordinate(coordinate: CLLocationCoordinate2D, radius: Double, name : String){
var urlString = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=\(apiServerKey)&location=\(coordinate.latitude),\(coordinate.longitude)&radius=\(radius)&rankby=prominence&sensor=true"
urlString += "&name=\(name)"
urlString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
println(urlString)
if placesTask.taskIdentifier > 0 && placesTask.state == .Running {
placesTask.cancel()
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
placesTask = session.dataTaskWithURL(NSURL(string: urlString)!) {data, response, error in
println("inside.")
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if let json = NSJSONSerialization.JSONObjectWithData(data, options:nil, error:nil) as? NSDictionary {
if let results = json["results"] as? NSArray {
for rawPlace:AnyObject in results {
println(rawPlace)
self.results.append(rawPlace as! String)
}
}
}
self.placesTask.resume()
}
}
传递的坐标是当前位置的坐标。如果我执行上面的代码,什么也没有发生,但是生成的 url 是有效的。如果我把 url 放在 Google 中,我会得到正确的结果。但我的应用程序中没有显示任何内容。请帮我解决这个问题。请让我知道哪里错了!!!
您已将地点添加到结果数组,但您已执行任何操作来更新您的地图视图,例如,将标记添加到您的地图视图。
示例代码向地图视图添加标记:
let returnedPlaces: NSArray? = jsonResult["results"] as? NSArray
if returnedPlaces != nil {
for index in 0..<returnedPlaces!.count {
if let returnedPlace = returnedPlaces?[index] as? NSDictionary {
var placeName = ""
var latitude = 0.0
var longitude = 0.0
if let name = returnedPlace["name"] as? NSString {
placeName = name as String
}
if let geometry = returnedPlace["geometry"] as? NSDictionary {
if let location = geometry["location"] as? NSDictionary {
if let lat = location["lat"] as? Double {
latitude = lat
}
if let lng = location["lng"] as? Double {
longitude = lng
}
}
}
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(latitude, longitude)
marker.title = placeName
marker.map = self.mapView
}
}
}
您可以在 Swift 中查看 this tutorial 如何使用 Google 地图前往附近的地点。
只需设置您的 Latt、long 和 GoogleAPIKey。
NSString *urlString= [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=%@,%@&radius=2000&key=%@",lati,longi,kGoogleAPIKey];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (connectionError)
{
NSLog(@"Error");
}
else
{
NSDictionary *dictJson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSArray *arrayPlaces = [[NSArray alloc] initWithArray:[dictJson objectForKey:@"results"]];
NSLog("Place %@",arrayPlaces);
}
}];
此外,如果您想通过文本搜索地点,只需将 urlString 如下所示。
NSString *urlString = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/autocomplete/json?sensor=true&key=%@&language=en&input=%@&query=123+main+street&radius=50000&location=0.0,0.0&rankby=distance",kGoogleAPIKey,searchText];
在 arrayPlaces 中你有附近的地方。