Convert coordinates to City name?
SWIFT 4.2 : EDIT
MapKit
framework does provide a way to get address details from coordinates.
You need to use reverse geocoding of map kit. CLGeocoder
class is used to get the location from address and address from the location (coordinates). The method reverseGeocodeLocation
will returns the address details from coordinates.
This method accepts CLLocation
as a parameter and returns CLPlacemark
, which contains address dictionary.
So now above method will be updated as:
@objc func didLongPressMap(sender: UILongPressGestureRecognizer) {
if sender.state == UIGestureRecognizer.State.began {
let touchPoint = sender.location(in: mapView)
let touchCoordinate = mapView.convert(touchPoint, toCoordinateFrom: self.mapView)
let annotation = MKPointAnnotation()
annotation.coordinate = touchCoordinate
annotation.title = "Your position"
mapView.addAnnotation(annotation) //drops the pin
print("lat: \(touchCoordinate.latitude)")
let num = touchCoordinate.latitude as NSNumber
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 4
formatter.minimumFractionDigits = 4
_ = formatter.string(from: num)
print("long: \(touchCoordinate.longitude)")
let num1 = touchCoordinate.longitude as NSNumber
let formatter1 = NumberFormatter()
formatter1.maximumFractionDigits = 4
formatter1.minimumFractionDigits = 4
_ = formatter1.string(from: num1)
self.adressLoLa.text = "\(num),\(num1)"
// Add below code to get address for touch coordinates.
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: touchCoordinate.latitude, longitude: touchCoordinate.longitude)
geoCoder.reverseGeocodeLocation(location, completionHandler:
{
placemarks, error -> Void in
// Place details
guard let placeMark = placemarks?.first else { return }
// Location name
if let locationName = placeMark.location {
print(locationName)
}
// Street address
if let street = placeMark.thoroughfare {
print(street)
}
// City
if let city = placeMark.subAdministrativeArea {
print(city)
}
// Zip code
if let zip = placeMark.isoCountryCode {
print(zip)
}
// Country
if let country = placeMark.country {
print(country)
}
})
}
}
How can I get city name from a latitude and longitude point?
This is called Reverse Geocoding
Documentation from Google:
http://code.google.com/apis/maps/documentation/geocoding/#ReverseGeocoding.
Sample Call to Google's geocode Web Service:
http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true&key=YOUR_KEY
Convert GPS coordinates to a city name / address in Swift
You need to write the code like this:
geocoder.reverseGeocodeLocation(currentLocation, completionHandler: {
placemarks, error in
if error == nil && placemarks.count > 0 {
self.placeMark = placemarks.last as? CLPlacemark
self.adressLabel.text = "\(self.placeMark!.thoroughfare)\n\(self.placeMark!.postalCode) \(self.placeMark!.locality)\n\(self.placeMark!.country)"
self.manager.stopUpdatingLocation()
}
})
Converting latitude/longitude into city name? (reverse geolocating)
The Google Geocoder, which supports reverse geocoding returns address_components. You just need to pull out the component of the address tagged with locality
and political
if you just want the city name. If you want states as well they are tagged with administrative_area_level_1
Given the lat/long coordinates, how can we find out the city/country?
The free Google Geocoding API provides this service via a HTTP REST API. Note, the API is usage and rate limited, but you can pay for unlimited access.
Try this link to see an example of the output (this is in json, output is also available in XML)
https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true
Convert latitude and longitude to city names, using R
This is possible using the extract function from raster. Or also possible with the over function from the sp package. The approach I have taken below is done using the extract function:
I first used your data provided above to make a data frame, and then got the Brazil shapefile, and used it to extract the city name from the coordinates provided. Here is my code with comments:
library(raster)
library(sp)
#### Coordinates that will be used to search ###
state = c('AL','AL','AL','AL','AL','AL')
river = c('Rio Mundaú', 'Rio Mundaú', 'Rio Mundaú' , 'Zona dos Can', 'Zona dos Can', 'Zona dos Canais')
lat = c(-9.60, -9.60, -9.60, -9.71, -9.71, -9.71)
long = c(-35.8, -35.8, -35.8, -35.8, -35.8, -35.8)
year = c(2007, 2010, 2011, 2007, 2010, 2011)
contagem = c(5, 5, 9, 5, 7, 9)
mean = c(3, 2, 3.78, 2.2, 2, 2.11)
brazil_data = data.frame(state, river, lat, long, year, contagem, mean)
### Getting the brazil shapefile
brazil = getData('GADM', country = 'Brazil', level = 3, type = "sp")
### Extracting the attributes from the shapefile for the given points
city_names = extract(brazil, brazil_data[, c("long", "lat")])[,12]
### Adding the city names to the Brazil data frame, with the coordinates
brazil_data$City = city_names
This is what we get at the end:
> brazil_data
state river lat long year contagem mean City
1 AL Rio Mundaú -9.60 -35.8 2007 5 3.00 Santa Luzia do Norte
2 AL Rio Mundaú -9.60 -35.8 2010 5 2.00 Santa Luzia do Norte
3 AL Rio Mundaú -9.60 -35.8 2011 9 3.78 Santa Luzia do Norte
4 AL Zona dos Can -9.71 -35.8 2007 5 2.20 Marechal deodoro
5 AL Zona dos Can -9.71 -35.8 2010 7 2.00 Marechal deodoro
6 AL Zona dos Canais -9.71 -35.8 2011 9 2.11 Marechal deodoro
Hope this helps!
Converting a city name to coordinates in Swift
You can do it as follow:
import CoreLocation
func getCoordinateFrom(address: String, completion: @escaping(_ coordinate: CLLocationCoordinate2D?, _ error: Error?) -> () ) {
CLGeocoder().geocodeAddressString(address) { completion($0?.first?.location?.coordinate, $1) }
}
Usage:
let address = "Rio de Janeiro, Brazil"
getCoordinateFrom(address: address) { coordinate, error in
guard let coordinate = coordinate, error == nil else { return }
// don't forget to update the UI from the main thread
DispatchQueue.main.async {
print(address, "Location:", coordinate) // Rio de Janeiro, Brazil Location: CLLocationCoordinate2D(latitude: -22.9108638, longitude: -43.2045436)
}
}
Convert coordinates to a place name
The Google Maps API Docs have what seems to be a complete reverse geocoding example. (Note that this is the new V3 API!)
How to get city name from latitude and longitude coordinates in Google Maps?
From a Geocoder
object, you can call the getFromLocation(double, double, int)
method. It will return a list of Address
objects that have a method getLocality()
.
Geocoder gcd = new Geocoder(context, Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(lat, lng, 1);
if (addresses.size() > 0) {
System.out.println(addresses.get(0).getLocality());
}
else {
// do your stuff
}
Related Topics
How Programmatically Restart an iPhone App in iOS
Missing Marketing Icon Xcode Bug
Playing Back Audio Using Avaudioplayer iOS 7
Xcode UI Testing Error Keyboard
Tableview Cell How Do We Resize Cell in Swift Along with Image and Label
As3 for iOS:How to Serialize an Array and Then Save It
How to Resize Table Cell Based on Textview
How to Programmatically Get iOS Status Bar Height
Programmatically Go Back to Previous Viewcontroller in Swift
Multiline Label in Uistackview
Switching Viewcontrollers with Uisegmentedcontrol in iOS5
How to Get Core Data Object from Specific Object Id
Running Xcodebuild from a Forked Terminal
Uislider That Snaps to a Fixed Number of Steps (Like Text Size in the iOS 7 Settings App)
Uikeyboardboundsuserinfokey Is Deprecated, What to Use Instead