-2

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);
}  
Daniel
  • 147
  • 1
  • 7
  • 19

1 Answers1

0

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>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46