【问题标题】:Fetching nearby places using google maps使用谷歌地图获取附近的地方
【发布时间】:2015-04-14 20:22:35
【问题描述】:

我正在尝试使用谷歌地图查找我当前位置的附近地点。 我在 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 是有效的。如果我将该网址放在 Google 中,我会得到正确的结果。但我的应用程序中没有显示任何内容。请帮我解决这个问题。并请让我知道哪里错了!!!

【问题讨论】:

  • 如果我想搜索附近的图书馆怎么办?

标签: google-maps swift ios8 google-places-api google-maps-sdk-ios


【解决方案1】:

您将地点添加到结果数组中,但您已经做了任何事情来更新您的地图视图,例如,向您的地图视图添加标记。

示例代码添加标记到地图视图:

   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
                }
           }
   }

您可以查看this tutorial,了解如何在 Swift 中使用 Google 地图获取附近的地点。

【讨论】:

  • 您的请求网址是什么?
  • 你的self.placesTask.resume() 应该在你的dataTaskWithURL 方法闭包之外。
  • 哦,是的!!!!非常感谢 Ztan ....是的,我放在 dataTaskWithURL 中,这是一个愚蠢的错误..现在它工作正常...再次感谢!!!
  • 我按照上面给出的教程进行操作,但地图上没有加载这些地点。有人可以帮我吗?我已经安装到 pod 并且还更改了我的 api 密钥
【解决方案2】:

只需设置您的 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 你有附近的地方。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 2017-06-07
    • 1970-01-01
    相关资源
    最近更新 更多