如何使用地址设置Google Maps标记位置?

发布于 2025-01-28 20:30:00 字数 2595 浏览 3 评论 0原文

我是Google Maps API的新手,必须使用它来找到一些地址。我想知道如何将Google Maps标记在文本字段中写入地址。我一直在阅读Google的文档,但这并不是很有帮助。到目前为止,我设法根据标记运动的结束使标记移动并更新纬度和经度值。

在HTML中,我有:

<!-- Address input -->
<div class="col-md-3">
   <div class="form-group">
      <label for="example-text-input" class="form-control-label">Address</label>
      <input class="form-control" type="text" name="address" id="address">
   </div>
</div>

<!-- shows the current latitude -->
<div class="col-md-3">
    <div class="form-group">
         <label for="example-text-input" class="form-control-label">Lat</label>
         <input class="form-control" type="text" name="latitude" id="lat">
    </div>
</div>

<!-- shows the current longitude -->
<div class="col-md-3">
    <div class="form-group">
         <label for="example-text-input" class="form-control-label">Lng</label>
         <input class="form-control" type="text" name="longitude" id="lng">
    </div>
</div>

<!-- show the map -->
<div class="row">
     <div class="col">
        <div class="card border-0">
             <div id="map-default" class="map-canvas" style="height: 600px;"></div>
        </div>
     </div>
</div>

在JS上,我有一个:

var $map = $('#map-default'),
map,
lat,
lng,
color = "#5e72e4";

function initMap() {
     map = document.getElementById('map-default');

    map = new google.maps.Map(document.getElementById('map-default'), {
       zoom: 12,
       scrollwheel: true,
       center: new google.maps.LatLng(40.71427 , -74.00597),
       mapTypeId: google.maps.MapTypeId.ROADMAP,
    });

    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(4.60971, -74.08175),
        map: map,
        animation: google.maps.Animation.DROP,
        // title: 'Marcador',
        draggable: true
    });

    var infowindow = new google.maps.InfoWindow({
        content: String(marker.getPosition())
    });

    google.maps.event.addListener(marker, 'click', function(evt) {
        infowindow.open(map, marker); 
    });

    google.maps.event.addListener(marker, 'dragend', function(evt){
         $("#lat").val(evt.latLng.lat().toFixed(6));
         $("#lng").val(evt.latLng.lng().toFixed(6));

         map.panTo(evt.latLng);
    });

    map.setCenter(marker.position);

    marker.setMap(map);
}

if($map.length) {
    google.maps.event.addDomListener(window, 'load', initMap);
}  

I'm fairly new to the Google Maps API and have to use it to locate some addresses. I want to know how the Google Maps marker can be located with the address written in a text field. I've been reading Google's documentation on this, but it hasn't been very helpful.. So far I have managed to make the marker move and update the latitude and longitude values ​​according to the end of the marker movement.

In the html I have this:

<!-- Address input -->
<div class="col-md-3">
   <div class="form-group">
      <label for="example-text-input" class="form-control-label">Address</label>
      <input class="form-control" type="text" name="address" id="address">
   </div>
</div>

<!-- shows the current latitude -->
<div class="col-md-3">
    <div class="form-group">
         <label for="example-text-input" class="form-control-label">Lat</label>
         <input class="form-control" type="text" name="latitude" id="lat">
    </div>
</div>

<!-- shows the current longitude -->
<div class="col-md-3">
    <div class="form-group">
         <label for="example-text-input" class="form-control-label">Lng</label>
         <input class="form-control" type="text" name="longitude" id="lng">
    </div>
</div>

<!-- show the map -->
<div class="row">
     <div class="col">
        <div class="card border-0">
             <div id="map-default" class="map-canvas" style="height: 600px;"></div>
        </div>
     </div>
</div>

On the js I have this:

var $map = $('#map-default'),
map,
lat,
lng,
color = "#5e72e4";

function initMap() {
     map = document.getElementById('map-default');

    map = new google.maps.Map(document.getElementById('map-default'), {
       zoom: 12,
       scrollwheel: true,
       center: new google.maps.LatLng(40.71427 , -74.00597),
       mapTypeId: google.maps.MapTypeId.ROADMAP,
    });

    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(4.60971, -74.08175),
        map: map,
        animation: google.maps.Animation.DROP,
        // title: 'Marcador',
        draggable: true
    });

    var infowindow = new google.maps.InfoWindow({
        content: String(marker.getPosition())
    });

    google.maps.event.addListener(marker, 'click', function(evt) {
        infowindow.open(map, marker); 
    });

    google.maps.event.addListener(marker, 'dragend', function(evt){
         $("#lat").val(evt.latLng.lat().toFixed(6));
         $("#lng").val(evt.latLng.lng().toFixed(6));

         map.panTo(evt.latLng);
    });

    map.setCenter(marker.position);

    marker.setMap(map);
}

if($map.length) {
    google.maps.event.addDomListener(window, 'load', initMap);
}  

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

罗罗贝儿 2025-02-04 20:30:00

要查找标记地址(无论是基于点击事件,拖动事件还是静态LAT/LNG),您将需要使用 GeoCoder API - 但是请注意,这具有配额限制,并有助于地图使用统计信息! [请参阅此处的详细信息]

该过程被称为反向地理编码 - 地理编码器提供了LAT/LNG值,并将返回带有所选位置详细信息的JSON响应,您可以从中提取地址。

根据您的原始代码,但没有任何jQuery

<script>
    function initMap(){
        const map = new google.maps.Map(document.getElementById('map-default'), {
           zoom: 12,
           scrollwheel: true,
           center: new google.maps.LatLng( 40.71427 , -74.00597 ),
           mapTypeId: google.maps.MapTypeId.ROADMAP,
        });
        
        // initialise the GeoCoder
        const geocoder = new google.maps.Geocoder();
        const infowindow = new google.maps.InfoWindow();
        
        // utility to populate the input elements with discovered values
        const populate=( lat, lng, addr )=>{
            document.querySelector('input[name="address"]').value=addr;
            document.querySelector('input[name="latitude"]').value=lat.toFixed(6);
            document.querySelector('input[name="longitude"]').value=lng.toFixed(6);
        };
        
        // function to invoke the geocoder and find the address from given latlng
        const findlocation=(e)=>{
            geocoder.geocode( { 'location':e.latLng }, ( results, status )=>{
                return evtcallback( results, status, e.latLng);
            });         
        };
        
        // respond to clicks on the map
        const mapclickhandler=function(e){
            findlocation.call( this, e );
        };
        
        // respond to clicks on the marker
        const markerclickhandler=function(e){
            infowindow.open( map, this );
            infowindow.setContent( e.latLng.lat()+', '+e.latLng.lng() );
            if( this.hasOwnProperty('address') )infowindow.setContent( this.address );
        };
        
        // respond to drag events of the marker.
        const draghandler=function(e){
            findlocation.call( this, e );
            map.panTo( e.latLng );
        };
        
        
        // callback function that analyses the Geocoder response
        const evtcallback=function( results, status ){
            let _address, _location;
            if( status == google.maps.GeocoderStatus.OK ){
                _address=results[0].formatted_address;
                _location=results[0].geometry.location;

                
                // set custom properties for the marker 
                // which are used to populate infowindow
                marker.address=_address;
                marker.location=_location;
                
                // populate the HTML form elements
                populate( _location.lat(), _location.lng(), _address );
                
                // open and set content for the infowindow
                infowindow.open( map, marker );
                infowindow.setContent( _address );
                
                
                latlng=new google.maps.LatLng( _location.lat(), _location.lng() );
                marker.setPosition( latlng );
                map.setCenter( latlng );
                map.setZoom( 15 );
                return true;
            }
            console.warn( status );
        };
        
        
        let marker = new google.maps.Marker({
            position: new google.maps.LatLng( 4.60971, -74.08175 ),
            map: map,
            animation: google.maps.Animation.DROP,
            draggable: true
        });
        
        google.maps.event.addListener( map,'click', mapclickhandler );
        google.maps.event.addListener( marker, 'click', markerclickhandler );
        google.maps.event.addListener( marker, 'dragend', draghandler );
        map.setCenter( marker.position );
    }
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap"></script>

To find an address for the marker ( whether that is based upon a click event, drag event or static lat/lng ) you will need to use the Geocoder api - note however that this has a quota limit and contributes to the maps usage statistics! [ see here for details ]

The process is known as reverse geocoding - the geocoder is supplied with a lat/lng value and will return a JSON response with details of the chosen location, from which you can extract the address.

Based upon your original code but without any jQuery

<script>
    function initMap(){
        const map = new google.maps.Map(document.getElementById('map-default'), {
           zoom: 12,
           scrollwheel: true,
           center: new google.maps.LatLng( 40.71427 , -74.00597 ),
           mapTypeId: google.maps.MapTypeId.ROADMAP,
        });
        
        // initialise the GeoCoder
        const geocoder = new google.maps.Geocoder();
        const infowindow = new google.maps.InfoWindow();
        
        // utility to populate the input elements with discovered values
        const populate=( lat, lng, addr )=>{
            document.querySelector('input[name="address"]').value=addr;
            document.querySelector('input[name="latitude"]').value=lat.toFixed(6);
            document.querySelector('input[name="longitude"]').value=lng.toFixed(6);
        };
        
        // function to invoke the geocoder and find the address from given latlng
        const findlocation=(e)=>{
            geocoder.geocode( { 'location':e.latLng }, ( results, status )=>{
                return evtcallback( results, status, e.latLng);
            });         
        };
        
        // respond to clicks on the map
        const mapclickhandler=function(e){
            findlocation.call( this, e );
        };
        
        // respond to clicks on the marker
        const markerclickhandler=function(e){
            infowindow.open( map, this );
            infowindow.setContent( e.latLng.lat()+', '+e.latLng.lng() );
            if( this.hasOwnProperty('address') )infowindow.setContent( this.address );
        };
        
        // respond to drag events of the marker.
        const draghandler=function(e){
            findlocation.call( this, e );
            map.panTo( e.latLng );
        };
        
        
        // callback function that analyses the Geocoder response
        const evtcallback=function( results, status ){
            let _address, _location;
            if( status == google.maps.GeocoderStatus.OK ){
                _address=results[0].formatted_address;
                _location=results[0].geometry.location;

                
                // set custom properties for the marker 
                // which are used to populate infowindow
                marker.address=_address;
                marker.location=_location;
                
                // populate the HTML form elements
                populate( _location.lat(), _location.lng(), _address );
                
                // open and set content for the infowindow
                infowindow.open( map, marker );
                infowindow.setContent( _address );
                
                
                latlng=new google.maps.LatLng( _location.lat(), _location.lng() );
                marker.setPosition( latlng );
                map.setCenter( latlng );
                map.setZoom( 15 );
                return true;
            }
            console.warn( status );
        };
        
        
        let marker = new google.maps.Marker({
            position: new google.maps.LatLng( 4.60971, -74.08175 ),
            map: map,
            animation: google.maps.Animation.DROP,
            draggable: true
        });
        
        google.maps.event.addListener( map,'click', mapclickhandler );
        google.maps.event.addListener( marker, 'click', markerclickhandler );
        google.maps.event.addListener( marker, 'dragend', draghandler );
        map.setCenter( marker.position );
    }
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap"></script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文