6

Sto cercando di implementare per trovare luoghi nelle vicinanze della mia posizione corrente utilizzando Google Maps. Ho creato un progetto nella Google Developer Console e ho ricevuto "ios APIkey" e "Server APIkey". Ho anche attivato l'API di Google Places e l'SDK di Google Maps per iOS. Di seguito è riportato il codice per scoprire vicino a luoghi.Recupero di luoghi nelle vicinanze utilizzando Google Maps

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

La coordinata passata è la coordinata della posizione corrente. Se eseguo un codice sopra, non succede nulla, ma l'url generato è valido. Se metto quell'URL in Google sto ottenendo risultati corretti. Ma niente nella mia app. Per favore aiutami a risolvere questo. e per favore fatemi sapere dove sbaglio !!!

+0

E se volessi cercare le librerie vicine? –

risposta

9

Aggiungete i vostri posti all'array dei risultati, ma avete fatto qualcosa per aggiornare la vostra vista mappa, ad esempio aggiungendo marcatori alla vostra mappa.

codice di esempio aggiungere marcatore per mapview:

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

Si può vedere this tutorial su come ottenere posti vicini con Google Maps a Swift.

+0

Grazie per la risposta Ztan !!! Ma non restituisce alcun posto :( –

+0

Qual è l'URL della richiesta? – ztan

+0

Anche il tuo 'self.placesTask.resume()' dovrebbe essere al di fuori della chiusura del metodo 'dataTaskWithURL'. – ztan

0

Basta impostare Latt, long e 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); 

     } 
    }]; 

Inoltre, se si desidera cercare posto per il testo, Basta fare urlString come di seguito.

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]; 

In arrayPlaces ci sono luoghi nelle vicinanze.

Problemi correlati