I have a query regarding clgeocoder apis , basically in our app we have a provision to add address manually by user by giving region, city and place details etc; when I try to fetch lat long values via CLgeocoder geocodeAddressString api its throwing following error Error Domain=kCLErrorDomain Code=8 "(null)" (Here the region selected is peru). When i change region to India in device and add address manually it works and iam able to fetch lat long values.
Iam attaching code below for reference
Can some one help to resolve this region specific issue
func getLatLong () {
let address = " 1850, Av. angamos este , Municipalidad Metropolitana de Lima, Surquillo, PERU"
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
if error == nil {
print(placemarks)
} else {
print(error)
}
}
}
ima expecting to receive lat long values irrespective of selected region in device
Here is my test code, create a new XCode project (ios) and use this example code.
All works well for me, on MacOS 13.2, Xcode 14.2, tested on real ios 16.3 devices (not Previews), and macCatalyst.
import Foundation
import SwiftUI
import CoreLocation
struct ContentView: View {
#State var txt = ""
var body: some View {
Text(txt)
.onAppear {
getLatLong()
}
}
func getLatLong() {
let address = " 1850, Av. angamos este , Municipalidad Metropolitana de Lima, Surquillo, PERU"
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
if error == nil {
print("\n---> placemarks: \(placemarks)\n")
if let first = placemarks?.first,
let coord = first.location?.coordinate {
txt = "lat: \(coord.latitude) lon: \(coord.longitude)"
}
} else {
print("\n---> error: \(error)\n")
}
}
}
}
Related
I am implementing ForwardGeocodeOptions in my iOS sample app using MAPBOX SDK. And I am making a call for getting Placemarks. But always getting 10 results only. I want to get minimum 30 results or more than that. How can I get ?
func getResults(){
let options = ForwardGeocodeOptions(query: "restaurant")
// options.allowedISOCountryCodes = ["IN"]
options.focalLocation = CLLocation(latitude: 17.4447496, longitude: 78.3136091)
options.allowedScopes = [.pointOfInterest,.all]
options.maximumResultCount = 50
let task = Geocoder.shared.geocode(options) {(placemarks, attribution, error) in
if let error = error {
NSLog("%#", error)
} else if let placemarks = placemarks, !placemarks.isEmpty {
print(" \(placemarks.count)")
}
}
task.resume()
}
Internally calling this API :-
https://api.mapbox.com/geocoding/v5/mapbox.places/restaurant.json?proximity=78.3817464,17.446809&types=all&limit=50&access_token=[access_token_here]
Per the API docs, 10 is the upper limit for a forward geocoding request. You’re free to make multiple requests with different parameters.
I need to convert my Latitude and longitude to address to extract so data from it
here is my method but this fail with error {The operation couldn’t be completed. (com.google.HTTPStatus error 400.)}
void ConvertLatLong(double latitude, double longitude)
{
try
{
Geocoder geocoder;
CLLocationCoordinate2D location = new CLLocationCoordinate2D(latitude, longitude);
geocoder = new Geocoder();
geocoder.ReverseGeocodeCord(location ,(response, error) => {
if (error != null) return;
var addresses = response.Results;
if (addresses != null && addresses.Length > 1)
{
Address selectedAddress = addresses[1];
if (selectedAddress.AdministrativeArea != null)
{
var citySelected = citiesLookupResult.Find(c => (selectedAddress.AdministrativeArea.Contains(c.NameEn)));
chooseCity.Text = citySelected.NameEn;
}
}
});
}
catch (Exception e)
{
}
}
my tries to fix this issue
First I make sure that my bundle name is matched between google console and my application
Second make sure I set my E-mail , app name under Credential --> oAuth consent screen
any one could help me with my issue
Possible solutions
Enable GoogleMap SDK for iOS Here
Register Api key for GMSServices in didFinishLaunchingWithOptions.
Check that your API key is valid for your bundle id on console.developer.google.com.
I'm adding my interested Place to Google Place with my APP. Place is getting added successfully, but the address field is empty.
Here is Code:
{
GMSPlacesClient.provideAPIKey(googlePlaceAPIKEY)
let placesClient = GMSPlacesClient.shared()
let userAddedPlace = GMSUserAddedPlace()
userAddedPlace.name = "NightClub & Bar"
userAddedPlace.address = "48 Gandhi Road, Bandra, Mumbai, Maharastra"
userAddedPlace.coordinate = CLLocationCoordinate2DMake(19.017615 , 72.856164)
userAddedPlace.phoneNumber = "9999999999"
userAddedPlace.website = "http://www.google.com/"
userAddedPlace.types = ["bar"]
placesClient.add(userAddedPlace, callback: { (place, error) -> Void in
if let error = error {
print("Add Place error: \(error)")
return
}
if let place = place {
print("Added place with placeID \(place.placeID)")
}
})
}
I can see "NightClub & Bar" in my place list but the address "48 Gandhi Road, Bandra, Mumbai, Maharastra" is not there.
Can anyone tell me what mistake I made?
My code:
let req = MKDirectionsRequest()
req.source = MKMapItem.mapItemForCurrentLocation()
req.destination = destination
let dir = MKDirections(request:req)
if dir.calculating {
print("calculating")
} else {
print("Not Calculating")
}
dir.calculateDirectionsWithCompletionHandler() {
(response:MKDirectionsResponse?, error:NSError?) in
When I print error it shows following:
Error Domain=MKErrorDomain Code=1 "Directions Not Available" UserInfo={NSLocalizedFailureReason=Route information is not available at this moment., NSLocalizedDescription=Directions Not Available, MKDirectionsErrorCode=2, MKErrorGEOError=-902}
It always throws the error above.
I cannot get what those error keys are:
MKErrorGEOError = -902
MKDirectionsErrorCode=2
Googled for more info in it couldn't find it.
I'm trying to save a CKRecord with a location field along with it but when ever I try to it crashes. Here's the code I'm using (crashes where it says: // CRASHES HERE):
func saveStateMood(stateToSave:String) {
// Create CK record
let newRecord:CKRecord = CKRecord(recordType: "State")
let newLocation:CKLocationSortDescriptor = CKLocationSortDescriptor(key: "Loco", relativeLocation: self.theState)
newRecord.setValue(stateToSave, forKey: "State")
newRecord.setValue(newLocation, forKey: "Loco") // CRASHES HERE!!!!!!
// Save record into public database
if let database = self.publicDatabase {
database.saveRecord(newRecord, completionHandler: { (record:CKRecord!, error:NSError!) -> Void in
// Check for error
if error != nil {
// There was an error
NSLog(error.localizedDescription)
}
else {
// There was no error
dispatch_async(dispatch_get_main_queue()) {
// Refresh table
//self.retrieveStateMoods("")
}
}
})
}
}
(I'm using the CLGeocoder to find the current location then I assign the current location to "theState")
I'm trying to follow the CloudKit Quick Start guideline for adding location fields but it is all written in Obj-C and I can't seem to figure it out and I also can't figure out how to fetch the records by their location field either.
You need to store an instance of CLLocation in your record. But you are trying to save an instance of CKLocationSortDescriptor. Update your code to use CLLocation.