简体   繁体   English

如何使用地址设置谷歌地图标记位置?

[英]how to set Google Maps marker position with the address?

I'm fairly new to the Google Maps API and have to use it to locate some addresses.我对 Google Maps API 相当陌生,必须使用它来定位一些地址。 I want to know how the Google Maps marker can be located with the address written in a text field.我想知道如何使用写在文本字段中的地址来定位 Google 地图标记。 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:在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>

On the js I have this:在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);
}  

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!要找到标记的地址(无论是基于单击事件、拖动事件还是静态 lat/lng),您需要使用Geocoder api - 但请注意,这有配额限制并有助于地图使用统计! [ 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.该过程称为reverse geocoding - 地理编码器提供了一个 lat/lng 值,并将返回一个 JSON 响应,其中包含所选位置的详细信息,您可以从中提取地址。

Based upon your original code but without any jQuery基于您的原始代码,但没有任何 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM