위도 / 경도 좌표가 주어지면 도시 / 국가를 어떻게 알 수 있습니까?
예를 들어이 좌표 세트가 있다면
"latitude": 48.858844300000001,
"longitude": 2.2943506,
도시 / 국가를 어떻게 알 수 있습니까?
무료 Google 지오 코딩 API 는 HTTP REST API를 통해이 서비스를 제공합니다. API는 사용량과 요금이 제한 되어 있지만 무제한 액세스 비용을 지불 할 수 있습니다.
이 링크를 시도하여 출력 예제를보십시오 (이것은 json에 있고 출력은 XML에서도 가능합니다)
https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true
다른 옵션 :
- http://download.geonames.org/export/dump/ 에서 도시 데이터베이스를 다운로드 하십시오.
- 각 도시를 위도 / 경도-> 도시 매핑으로 R- 트리와 같은 공간 인덱스에 추가합니다 (일부 DB도 기능이 있음)
- 가장 가까운 이웃 검색을 사용하여 특정 지점에서 가장 가까운 도시를 찾습니다
장점 :
- 사용 가능한 외부 서버에 의존하지 않습니다
- 매우 빠름 (초당 수천 번의 조회를 쉽게 수행)
단점 :
- 자동으로 최신이 아님
- 가장 가까운 도시가 수십 마일 떨어져있는 경우를 구별하려면 추가 코드가 필요합니다.
- 극과 국제 날짜 표시 줄 근처에서 이상한 결과를 낼 수 있습니다 (어쨌든 그 도시에는 도시가 없지만
당신은 필요 geopy
pip install geopy
그리고:
from geopy.geocoders import Nominatim
geolocator = Nominatim()
location = geolocator.reverse("48.8588443, 2.2943506")
print(location.address)
자세한 정보를 얻으려면 :
print (location.raw)
{'place_id': '24066644', 'osm_id': '2387784956', 'lat': '41.442115', 'lon': '-8.2939909', 'boundingbox': ['41.442015', '41.442215', '-8.2940909', '-8.2938909'], 'address': {'country': 'Portugal', 'suburb': 'Oliveira do Castelo', 'house_number': '99', 'city_district': 'Oliveira do Castelo', 'country_code': 'pt', 'city': 'Oliveira, São Paio e São Sebastião', 'state': 'Norte', 'state_district': 'Ave', 'pedestrian': 'Rua Doutor Avelino Germano', 'postcode': '4800-443', 'county': 'Guimarães'}, 'osm_type': 'node', 'display_name': '99, Rua Doutor Avelino Germano, Oliveira do Castelo, Oliveira, São Paio e São Sebastião, Guimarães, Braga, Ave, Norte, 4800-443, Portugal', 'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright'}
오픈 소스 대안은 Open Street Map의 Nominatim입니다. URL에 변수를 설정하기 만하면 해당 위치의 도시 / 국가가 반환됩니다. 공식 문서는 다음 링크를 확인하십시오 : Nominatim
비슷한 기능을 찾고 있었고 이전 응답에서 공유 된 " http://download.geonames.org/export/dump/ " 데이터를 보았습니다 (공유해 주셔서 감사합니다. 훌륭한 소스입니다). 도시 1000.txt 데이터.
당신은 그것을 실행 볼 수 있습니다 http://scatter-otl.rhcloud.com/location?lat=36&long=-78.9 (깨진 링크) 위치의 위도와 경도를 변경하십시오.
OpenShift (RedHat 플랫폼)에 배포됩니다. 유휴 기간이 지난 후 첫 통화는 시간이 걸릴 수 있지만 일반적으로 성능은 만족 스럽습니다. 이 서비스를 원하는대로 사용하십시오 ...
또한 https://github.com/turgos/Location 에서 프로젝트 소스를 찾을 수 있습니다 .
Google, Geonames 및 OpenStreetMaps를 비롯한 여러 공급자를 지원하는 훌륭한 Python 라이브러리 인 Geocoder를 사용 하여 몇 가지 를 언급했습니다 . GeoPy 라이브러리를 사용해 보았는데 종종 시간 초과가 발생합니다. GeoNames에 대한 자신의 코드를 개발하는 것이 시간을 가장 잘 사용하지 않으므로 코드가 불안정해질 수 있습니다. 지오 코더는 내 경험에서 사용하기가 매우 간단하고 충분한 문서를 가지고 있습니다 . 다음은 위도와 경도로 도시를 조회하거나 도시 이름으로 위도 / 경도를 찾기위한 샘플 코드입니다.
import geocoder
g = geocoder.osm([53.5343609, -113.5065084], method='reverse')
print g.json['city'] # Prints Edmonton
g = geocoder.osm('Edmonton, Canada')
print g.json['lat'], g.json['lng'] # Prints 53.5343609, -113.5065084
Javascript 에서이 작업을 수행하는 방법에 대한 코드 예제를 찾으려고 약 30 분을 보냈습니다. 게시 한 질문에 대한 명확한 답변을 찾을 수 없습니다. 그래서 ... 나는 내 자신을 만들었습니다. 잘만되면 사람들은 API를 읽거나 읽을 줄 모르는 코드를 보지 않고도 이것을 사용할 수 있기를 바랍니다. 하 아무것도 내 자신의 물건에 대 한이 게시물을 참조 할 수없는 경우 .. 토론 포럼에 대 한 좋은 질문과 감사합니다!
이것은 구글 API를 활용하고 있습니다.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=<YOURGOOGLEKEY>&sensor=false&v=3&libraries=geometry"></script>
.
//CHECK IF BROWSER HAS HTML5 GEO LOCATION
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
//GET USER CURRENT LOCATION
var locCurrent = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
//CHECK IF THE USERS GEOLOCATION IS IN AUSTRALIA
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': locCurrent }, function (results, status) {
var locItemCount = results.length;
var locCountryNameCount = locItemCount - 1;
var locCountryName = results[locCountryNameCount].formatted_address;
if (locCountryName == "Australia") {
//SET COOKIE FOR GIVING
jQuery.cookie('locCountry', locCountryName, { expires: 30, path: '/' });
}
});
}
}
실제로 어떤 기술 제한이 있는지에 달려 있습니다.
한 가지 방법은 관심있는 국가 및 도시의 개요가있는 공간 데이터베이스를 갖는 것입니다. 개요 적으로 국가 및 도시는 공간 유형 다각형으로 저장됩니다. 좌표 세트를 공간 유형 점으로 변환하고 다각형에 대해 쿼리하여 점이있는 국가 / 도시 이름을 얻을 수 있습니다.
Here are some of the databases which support spatial type: SQL server 2008, MySQL, postGIS - an extension of postgreSQL and Oracle.
If you would like to use a service in stead of having your own database for this you can use Yahoo's GeoPlanet. For the service approach you might want to check out this answer on gis.stackexchange.com, which covers the availability of services for solving your problem.
I know this question is really old, but I have been working on the same issue and I found an extremely efficient and convenient package, reverse_geocoder
, built by Ajay Thampi. The code is available here. It based on a parallelised implementation of K-D trees which is extremely efficient for large amounts of points (it took me few seconds to get 100,000 points.
It is based on this database, already highlighted by @turgos.
If your task is to quickly find the country and city of a list of coordinates, this is a great tool.
You can use Google Geocoding API
Bellow is php function that returns Adress, City, State and Country
public function get_location($latitude='', $longitude='')
{
$geolocation = $latitude.','.$longitude;
$request = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$geolocation.'&sensor=false';
$file_contents = file_get_contents($request);
$json_decode = json_decode($file_contents);
if(isset($json_decode->results[0])) {
$response = array();
foreach($json_decode->results[0]->address_components as $addressComponet) {
if(in_array('political', $addressComponet->types)) {
$response[] = $addressComponet->long_name;
}
}
if(isset($response[0])){ $first = $response[0]; } else { $first = 'null'; }
if(isset($response[1])){ $second = $response[1]; } else { $second = 'null'; }
if(isset($response[2])){ $third = $response[2]; } else { $third = 'null'; }
if(isset($response[3])){ $fourth = $response[3]; } else { $fourth = 'null'; }
if(isset($response[4])){ $fifth = $response[4]; } else { $fifth = 'null'; }
$loc['address']=''; $loc['city']=''; $loc['state']=''; $loc['country']='';
if( $first != 'null' && $second != 'null' && $third != 'null' && $fourth != 'null' && $fifth != 'null' ) {
$loc['address'] = $first;
$loc['city'] = $second;
$loc['state'] = $fourth;
$loc['country'] = $fifth;
}
else if ( $first != 'null' && $second != 'null' && $third != 'null' && $fourth != 'null' && $fifth == 'null' ) {
$loc['address'] = $first;
$loc['city'] = $second;
$loc['state'] = $third;
$loc['country'] = $fourth;
}
else if ( $first != 'null' && $second != 'null' && $third != 'null' && $fourth == 'null' && $fifth == 'null' ) {
$loc['city'] = $first;
$loc['state'] = $second;
$loc['country'] = $third;
}
else if ( $first != 'null' && $second != 'null' && $third == 'null' && $fourth == 'null' && $fifth == 'null' ) {
$loc['state'] = $first;
$loc['country'] = $second;
}
else if ( $first != 'null' && $second == 'null' && $third == 'null' && $fourth == 'null' && $fifth == 'null' ) {
$loc['country'] = $first;
}
}
return $loc;
}
Please check the below answer. It works for me
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
initialize(position.coords.latitude,position.coords.longitude);
});
}
function initialize(lat,lng) {
//directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
//directionsService = new google.maps.DirectionsService();
var latlng = new google.maps.LatLng(lat, lng);
//alert(latlng);
getLocation(latlng);
}
function getLocation(latlng){
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var loc = getCountry(results);
alert("location is::"+loc);
}
}
});
}
function getCountry(results)
{
for (var i = 0; i < results[0].address_components.length; i++)
{
var shortname = results[0].address_components[i].short_name;
var longname = results[0].address_components[i].long_name;
var type = results[0].address_components[i].types;
if (type.indexOf("country") != -1)
{
if (!isNullOrWhitespace(shortname))
{
return shortname;
}
else
{
return longname;
}
}
}
}
function isNullOrWhitespace(text) {
if (text == null) {
return true;
}
return text.replace(/\s/gi, '').length < 1;
}
If you are using Google's Places API, this is how you can get country and city from the place object using Javascript:
function getCityAndCountry(location) {
var components = {};
for(var i = 0; i < location.address_components.length; i++) {
components[location.address_components[i].types[0]] = location.address_components[i].long_name;
}
if(!components['country']) {
console.warn('Couldn\'t extract country');
return false;
}
if(components['locality']) {
return [components['locality'], components['country']];
} else if(components['administrative_area_level_1']) {
return [components['administrative_area_level_1'], components['country']];
} else {
console.warn('Couldn\'t extract city');
return false;
}
}
Loc2country is a Golang based tool that returns the ISO alpha-3 country code for given location coordinates (lat/lon). It responds in microseconds. It uses a geohash to country map.
The geohash data is generated using georaptor.
We use geohash at level 6 for this tool, i.e., boxes of size 1.2km x 600m.
'programing tip' 카테고리의 다른 글
문자열에서 줄 바꿈 (문자 없음)을 제거하는 방법은 무엇입니까? (0) | 2020.06.30 |
---|---|
NSManagedObject의 특정 하위 클래스를 찾을 수 없습니다 (0) | 2020.06.29 |
기본 long 배열을 Long 목록으로 변환 (0) | 2020.06.29 |
분기가없는 Git 커밋 나열 및 삭제 (댕글?) (0) | 2020.06.29 |
jQuery를 사용하여 선택 상자에서 첫 번째 옵션을 설정하는 방법은 무엇입니까? (0) | 2020.06.29 |