2017-10-21 1 views
5

주소가있는 장소의 데이터베이스가 있고 Google지도에 마커를 추가하고 싶습니다.Google지도 API - 주소로 마커 추가 javascript

기본 마커 만 표시되며 geocoder.geocode()는 아무 것도하지 않는 것처럼 보입니다. 예를 들어 "뉴욕시"에 마커를 추가하려고하는데 성공하지 못했습니다.

<script> 
    var geocoder; 
    var map; 
    var address = "new york city"; 
    geocoder = new google.maps.Geocoder(); 
    function initMap() { 
     var uluru = { lat: -25.363, lng: 131.044 }; 
     var map = new google.maps.Map(document.getElementById('map'), { 
      zoom: 4, 
      center: uluru 
     }); 
     var marker = new google.maps.Marker({ 
      position: uluru, 
      map: map 
     }); 
     codeAddress(address); 

    } 

    function codeAddress(address) { 

     geocoder.geocode({ 'address': address }, function (results, status) { 
      if (status == 'OK') { 
        var marker = new google.maps.Marker({ 
        position: address, 
        map: map 
       }); 
      } else { 
       alert('Geocode was not successful for the following reason: ' + status); 
      } 
     }); 
    } 


</script> 
<script src="https://maps.googleapis.com/maps/api/js?key=XXX&callback=initMap" 
    async defer></script> 

답변

4

사용자가 예상 한 결과를 얻지 못하는 이유는 제공된 예제에 잘못된 코드 배치가 있기 때문입니다. Google지도가 완전히로드되기 전에 Google지도 API 지오 코더의 새 인스턴스를 가져 오려고합니다. 따라서 Google지도 API 지오 코더가 작동하지 않습니다. Uncaught ReferenceError : google이 정의되지 않았습니다.. initMap() 함수 내에 Google Maps API Geocoder의 새 인스턴스를 가져와야합니다.

자세한 내용은 Maps JavaScript API Geocoding 을 확인하십시오.

Best Practices When Geocoding Addresses을 확인할 수도 있습니다.

Google지도 APi 관련 질문을 게시 할 때 API_KEY를 포함하면 안됩니다.

<!DOCTYPE html> 
<html> 
    <head> 
    <title>Geocoding service</title> 
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> 
    <meta charset="utf-8"> 
    <style> 
     /* Always set the map height explicitly to define the size of the div 
     * element that contains the map. */ 
     #map { 
     height: 100%; 
     } 
     /* Optional: Makes the sample page fill the window. */ 
     html, body { 
     height: 100%; 
     margin: 0; 
     padding: 0; 
     } 
    </style> 
    </head> 
    <body> 
    <div id="map"></div> 
    <script> 
     var geocoder; 
     var map; 
     var address = "new york city"; 
     function initMap() { 
     var map = new google.maps.Map(document.getElementById('map'), { 
      zoom: 8, 
      center: {lat: -34.397, lng: 150.644} 
     }); 
     geocoder = new google.maps.Geocoder(); 
     codeAddress(geocoder, map); 
     } 

     function codeAddress(geocoder, map) { 
     geocoder.geocode({'address': address}, function(results, status) { 
      if (status === 'OK') { 
      map.setCenter(results[0].geometry.location); 
      var marker = new google.maps.Marker({ 
       map: map, 
       position: results[0].geometry.location 
      }); 
      } else { 
      alert('Geocode was not successful for the following reason: ' + status); 
      } 
     }); 
     } 
    </script> 
    <script async defer 
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"> 
    </script> 
    </body> 
</html> 

라이브 데모 here :

여기에 전체 코드입니다.

희망 하시겠습니까?

+0

위대한 - 내 대답을 받거나 상향 투표 하시겠습니까? 감사합니다 – rafon

+0

물론 나는 이미 투표를 한 적이 있지만 더 많은 평판 포인트를 얻을 때만 자리를 잡을 것입니다. –

+0

방금 ​​질문을 너무 많이 읽었습니다. 당신이 이미 15 명 이상이라고 생각했기 때문입니다. 그것이 더 높은 담당자를 필요로하지 않는 것을 받아들이는 것 :) – rafon

1

코드에 몇 가지 오류가 있습니다. 일반적으로, 그것은해야 지금 확인 같습니다

  • Google지도 API가 완전히로드 할 때 당신은 당신의 지오를 초기화해야한다 :

    var geocoder; 
    var map; 
    var address = "new york city"; 
    
    function initMap() { 
        geocoder = new google.maps.Geocoder(); 
    
        var uluru = { lat: -25.363, lng: 131.044 }; 
        map = new google.maps.Map(document.getElementById('map'), { 
         zoom: 4, 
         center: uluru 
        }); 
        var marker = new google.maps.Marker({ 
         position: uluru, 
         map: map 
        }); 
        codeAddress(address); 
    
    } 
    
    function codeAddress(address) { 
    
        geocoder.geocode({ 'address': address }, function (results, status) { 
         console.log(results); 
         var latLng = {lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng()}; 
         console.log (latLng); 
         if (status == 'OK') { 
          var marker = new google.maps.Marker({ 
           position: latLng, 
           map: map 
          }); 
          console.log (map); 
         } else { 
          alert('Geocode was not successful for the following reason: ' + status); 
         } 
        }); 
    } 
    

    이렇게하면 오류의 목록입니다. 즉,이 코드 행을 에 geocoder = new google.maps.Geocoder(); 입력해야합니다.

  • 지도를 초기화 할 때 전역 변수를 참조해야합니다. 코드에서 함수에 새 변수 맵을 만듭니다. 그러나 글로벌 변수 맵을 통과해야합니다.
  • 지오 코더 결과의 위치를 ​​가져 오려면이 코드 줄을 통과해야합니다 (results[0].geometry.location.lat()).

documentation을 참조하십시오.

질문이 있으시면 알려주십시오.