위도 / 경도 좌표가 주어지면 도시 / 국가를 어떻게 알 수 있습니까?


141

예를 들어이 좌표 세트가 있다면

"latitude": 48.858844300000001,
"longitude": 2.2943506,

도시 / 국가를 어떻게 알 수 있습니까?


2
아마 일종의 데이터베이스가 필요할 것입니다. Google Maps API를 직접 사용 해보고 싶습니다. 위도 / 경도를 지원합니다.
— beatgammit

답변:


96

무료 Google 지오 코딩 API 는 HTTP REST API를 통해이 서비스를 제공합니다. API는 사용량과 요금이 제한 되어 있지만 무제한 액세스 비용을 지불 할 수 있습니다.

출력의 예를 보려면이 링크를 시도하십시오 (이것은 json이고 출력은 XML로도 사용 가능합니다)

https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true


이것이 내가 갈 수 있기 때문에 이것을 받아들이는 것 :) Michael의 대답은 확실히 훌륭한 옵션입니다!
— ming yeow

5
Google의 역 지오 코딩은 Google지도와 함께 만 허용됩니다. 그러한 제한이없는 솔루션을 원한다면 (상업용이지만 미국 도시 만 있음) checkgeo.com
— James D

mapquest api는 경우에 따라 속도 제한이 없으며 다양한 지오 코딩 요구에 대해 매우 높은 속도 제한이 있기 때문에 또 다른 옵션입니다.
— Tom

2
무료 는 논란의 여지가 있으며 특정 제한 하에서 만 무료입니다.
— Petah

@JamesD : API 정책에 따르면 데이터를지도에 표시하는 경우 Google지도 여야하지만지도에 표시 할 필요는 없습니다.
— user276648

173

다른 옵션 :

  • http://download.geonames.org/export/dump/ 에서 도시 데이터베이스를 다운로드 하십시오.
  • 각 도시를 위도 / 경도-> 도시 매핑으로 R- 트리와 같은 공간 인덱스에 추가합니다 (일부 DB에도 기능이 있음)
  • 가장 가까운 이웃 검색을 사용하여 특정 지점에서 가장 가까운 도시를 찾습니다

장점 :

  • 사용 가능한 외부 서버에 의존하지 않습니다
  • 매우 빠름 (초당 수천 번의 조회를 쉽게 수행)

단점 :

  • 자동으로 최신이 아님
  • 가장 가까운 도시가 수십 마일 떨어져있는 경우를 구별하려면 추가 코드가 필요합니다.
  • 기둥과 국제 날짜 표시 줄 근처에 이상한 결과를 줄 수 있습니다 (어쨌든 그 도시에는 도시가 없지만

5
예를 들어 로마의 특정 위치는 각 데이터베이스에 지정된 위도 / 경도에 따라 "바티칸 시티"를 반환 할 수 있습니다.
— Noel Abrahams

1
그들은 또한 REST api를 가지고 있고 꽤 괜찮아
— jeudyx

8
예를 들자면 귀중했을 것입니다
— Hack-R

GeoNames는 또한 무료로 제공되는 무료 웹 서비스를 제공합니다!
— mcont

2020 년에 GeoNames.org는 거의 작동하지 않는 것으로 보입니다. 문제는 그들이 사이트의 마지막 업데이트 날짜를 언급하지 않습니다.
— joedotnot

45

당신은 필요 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'}

2
이것에 대한 제한이 있습니까? 이것은 가장 빠른 접근법 인 것 같습니다. @Michael의 접근법보다 이것을 사용하지 않을 이유가 있습니까?
— Satys

1
잘은 외부 서비스가 필요합니다
— maxbachmann

훌륭한 접근 방법이지만 카운티가 필요하므로 주소를 수정해야합니다. 나는 군을 돌려주는 방법이 있었으면 좋겠다.
— Fatemeh Asgarinejad

22

오픈 소스 대안은 Open Street Map의 Nominatim입니다. URL에 변수를 설정하기 만하면 해당 위치의 도시 / 국가가 반환됩니다. 공식 문서는 다음 링크를 확인하십시오 : Nominatim


3
Nominatim 사용 정책 operations.osmfoundation.org/policies/nominatim 은 초당 최대 하나의 요청 속도를 나타내므로 임시 쿼리에만 적합합니다.
— Matthew Wise

22

비슷한 기능을 찾고 있었고 이전 응답에서 공유 된 " 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 에서 프로젝트 소스를 찾을 수 있습니다 .


제대로 작동하지 않습니다. 도시를 찾을 수 없으면 가장 가까운 알려진 도시를 검색합니다. 예는 다음과 같습니다. scatter-otl.rhcloud.com/… "Saint John"대신 "Basseterre"라고 표시됩니다.
— smartmouse

1
맞습니다. 알고리즘은 데이터 세트에서 사용 가능한 가장 가까운 도시를 검색합니다. 위에 배포 된 서버에는 "cities1000.txt"를 사용했습니다. 주요 도시 만 있습니다. 소스 코드는 github.com/turgos/Location에 있습니다. " download.geonames.org/export/dump " 에서보다 자세한 데이터로 자신을 시작할 수 있습니다 .
— turgos

city1000.txt가 사용 가능한보다 자세한 데이터 인 것 같습니다. 내가 맞아?
— smartmouse

8

Google, Geonames 및 OpenStreetMaps를 비롯한 여러 공급자를 지원하는 훌륭한 Python 라이브러리 인 Geocoder를 사용 하여 몇 가지 를 언급했습니다 . GeoPy 라이브러리를 사용해 보았는데 종종 시간 초과가 발생합니다. GeoNames에 대한 자신의 코드를 개발하는 것이 시간을 가장 잘 사용하지 않으므로 코드가 불안정해질 수 있습니다. 지오 코더 (Geocoder)는 내 경험에서 사용하기가 매우 간단하고 충분한 문서가 있습니다. 다음은 위도와 경도로 도시를 조회하거나 도시 이름으로 위도 / 경도를 찾기위한 샘플 코드입니다.

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

이것을 공유해 주셔서 감사하지만 모든 좌표에서 작동하지는 않습니다. 좌표의 자릿수가 특정 크기 여야합니까?
— Fatemeh Asgarinejad

1
나는 경도와 위도를 올바르게 선택했다고 생각합니다. 임의의 좌표가 작동하지 않은 수천 개의 좌표가 있습니다. 이제 괜찮아 다른 접근법을 사용했습니다. 답변 주셔서 감사합니다.
— Fatemeh Asgarinejad

1
어서 오십시오. 어떤 접근법이 효과가 있었는지 궁금하십니까? 그것보다 더 있다면 geocoder, 나도 그것을 자신을 시도하고 싶습니다!
— Hamman Samuel

1
나는 이것을 사용했다 : geopy.geocoders import Nominatim geolocator = Nominatim () location = geolocator.reverse ( "41.4721, -72.6311") print (location.address) 전체 주소를 제공하고 카운티를 필터링합니다.
— Fatemeh Asgarinejad

1
고마워, 나는 큰 데이터 세트로 작업했고 2017 년 GeoPy를 사용하면 많은 시간 초과가 발생했습니다. 어쩌면 3 년 후에 그들은 제한을 풀었으므로 알기에 좋습니다!
— Hamman Samuel

5

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: '/' }); 
                }
        });
    }
}

5

나는이 질문이 실제로 오래되었다는 것을 알고 있지만 동일한 문제를 해결하고 reverse_geocoder있으며 Ajay Thampi가 제작 한 매우 효율적이고 편리한 패키지를 발견했습니다 . 코드는 여기에 있습니다 . 그것은 많은 양의 포인트에 대해 매우 효율적인 KD 트리의 병렬 구현을 기반으로합니다 (10 만 포인트를 얻는 데 몇 초가 걸렸습니다.

이 데이터베이스를 기반으로 하며 @turgos에 의해 이미 강조되어 있습니다.

좌표 목록의 국가와 도시를 신속하게 찾는 것이 유용한 도구입니다.


3

실제로 어떤 기술 제한이 있는지에 달려 있습니다.

한 가지 방법은 관심있는 국가 및 도시의 개요가있는 공간 데이터베이스를 갖는 것입니다. 개요 적으로 국가 및 도시는 공간 유형 다각형으로 저장됩니다. 좌표 세트를 공간 유형 점으로 변환하고 다각형에 대해 쿼리하여 점이있는 국가 / 도시 이름을 얻을 수 있습니다.

다음은 공간 유형을 지원하는 데이터베이스 중 일부입니다. SQL Server 2008 , MySQL , postGIS -postgreSQL 및 Oracle 의 확장입니다 .

자체 데이터베이스를 사용하는 대신 서비스를 사용하려면 Yahoo의 GeoPlanet을 사용할 수 있습니다 . 서비스 접근 방식의 경우 gis.stackexchange.com 에서이 답변 을 확인 하여 문제 해결을위한 서비스의 가용성을 다룰 수 있습니다.


1

Google 지오 코딩 API를 사용할 수 있습니다

Bellow는 Adress, City, State 및 Country를 반환하는 PHP 함수입니다.

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

administration_area_level_ 3 또는 지역 만 (admin_area_level_ 3을 사용할 수없는 경우) 원하는 경우 어느 것을 수정해야합니까? php ..의 새로운 기능
— 8

1

Loc2country 는 주어진 위치 좌표 (lat / lon)에 대한 ISO 알파 -3 국가 코드를 반환하는 Golang 기반 도구입니다. 마이크로 초 단위로 응답합니다. 지리 해시를 사용하여 국가지도에 표시합니다.

geohash 데이터는 georaptor를 사용하여 생성됩니다 .

이 도구에는 1.2km x 600m 크기의 상자에 대해 6 단계에서 geohash를 사용합니다.



0

아래 답변을 확인하십시오. 그것은 나를 위해 작동

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

0

Google의 Places API를 사용하는 경우 다음은 자바 스크립트를 사용하여 장소 객체에서 국가 및 도시를 가져올 수있는 방법입니다.

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;
  }
}
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.