Google 自动完成,第二个输入基于第一个结果

Google autocomplete, second inputs based on first one result

我需要一些有关 google 自动完成功能的帮助。我是一名后端开发人员,所以我在前端并不是很擅长 :D

我有 2 个自动完成输入(上车地址和下车地址)。我们在柏林有工作区,所以如果用户在柏林地区输入取货地址,投递地址可以是世界上任何其他地方如果用户在取货输入中输入柏林以外的地址,投递地址只需要在柏林地区。

我写了类似的东西,但真的很丑而且不能正常工作

  var polygon;
  var bounds;

  async function autocompletePickup() {
   
    polygon = new google.maps.Polygon({
      path: area,
      geodesic: true,
      strokeColor: '#FFd000',
      strokeOpacity: 1.0,
      strokeWeight: 4,
      fillColor: '#FFd000',
      fillOpacity: 0.35
    });

    var input = document.getElementById('pickup-address11');

    var autocomplete = new google.maps.places.Autocomplete(input);

      autocomplete.addListener('place_changed', function() {
        var place = autocomplete.getPlace();
    
        if (google.maps.geometry.poly.containsLocation(place.geometry.location, polygon)) {
          alert('The address is within'); 
          autocompleteDrop(1);
        } else {
          // alert('The address is outside of the area.'); 
          // input.value = "";
          // autocompleteDrop(withinArea=false);
        };
     });  
  }  


  async function autocompleteDrop(withinArea) {

    var inside = withinArea;
      
    polygon = new google.maps.Polygon({
      path: area,
      geodesic: true,
      strokeColor: '#FFd000',
      strokeOpacity: 1.0,
      strokeWeight: 4,
      fillColor: '#FFd000',
      fillOpacity: 0.35
    });

    if (inside === 1) {
      var input = document.getElementById('dropoff-address22');
      autocomplete = new google.maps.places.Autocomplete(input, options);
      input.addEventListener("change", function() {
          // input.value = "";
          console.log(inside);
      });
    } else {
      var input = document.getElementById('dropoff-address22');
      var autocomplete = new google.maps.places.Autocomplete(input);
      autocomplete.addListener('place_changed', function() {
          var place = autocomplete.getPlace();
          
          if (google.maps.geometry.poly.containsLocation(place.geometry.location, polygon)) {
            
          } else {
            alert('The drop off address is outside of our area.'); 
            input.value = "";
          };
       }); 
    } 
  }

  // berlin area
  var area = [
    { lat: 53.804069, lng: 14.124429 },
    { lat: 52.016925, lng: 13.959028 },
    { lat: 52.037322, lng: 11.438104 },
    { lat: 52.888570, lng: 8.804136 },
    { lat: 54.148454, lng: 9.626415 }
  ];

抱歉英语不好

我对 Google 地方 API 不是很熟悉,但我希望以下内容可能对解决问题有用。目前,如果接送地点被认为有效,下面的代码将只显示一个视觉指示器(更改文本字段背景颜色)。

<!doctype html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Google Maps: Places Auto-complete Berlin</title>
        <style>
            body,body *{box-sizing:border-box;font-family:monospace}
            #map{
                width:800px;
                height:600px;
                float:none;
                margin:auto;
            }
            form{width:800px;float:none;margin:1rem auto;}
            input{padding:0.5rem;}
            .ok{background:rgba(0,255,0,0.25);color:black}
            .bogus{background:rgba(255,0,0,0.25);color:white}
            label{display:inline-block;width:calc(50% - 4px);clear:none;margin:auto;}
        </style>
        <script>
            function initMap(){
                const oPick=document.querySelector('input[type="text"][name="pick"]');
                const oDrop=document.querySelector('input[type="text"][name="drop"]');
                const oResults=[];
                
                const BerlinRegion = [
                    { lat: 53.804069, lng: 14.124429 },
                    { lat: 52.016925, lng: 13.959028 },
                    { lat: 52.037322, lng: 11.438104 },
                    { lat: 52.888570, lng: 8.804136 },
                    { lat: 54.148454, lng: 9.626415 }
                ];
                
                /* create basic map */
                const latlng=new google.maps.LatLng( 0, 0 );
                const options = {
                    zoom: 1,
                    center:latlng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                const map=new google.maps.Map( document.getElementById('map'), options );
                const bounds=new google.maps.LatLngBounds();
                
                
                /* ensure we see the BerlinArea entirely */
                BerlinRegion.forEach( obj=>{
                    bounds.extend( obj );
                });
                map.fitBounds( bounds );
                
                /* display the area of operations */
                let polygon = new google.maps.Polygon({
                    path: BerlinRegion,
                    geodesic: true,
                    strokeColor: '#00FF00',
                    strokeOpacity: 1.0,
                    strokeWeight: 2,
                    fillColor: '#00FF00',
                    fillOpacity: 0.1,
                    map:map
                }); 
                
                
                const changehandler=function(){
                    // the same event handler can perform this task for both pickup & dropoff
                    let res=google.maps.geometry.poly.containsLocation( this.getPlace().geometry.location, polygon );
                    return testresults( res );
                };
                const addresult=function( res ){
                    // if the array is longer than 2, remove elements from the start of the array
                    while( oResults.length >= 2 )oResults.shift();
                    // add new item
                    oResults.push( res );
                };
                const testresults=function(r){
                    addresult(r);
                    
                    let b=false;//default return value
                    let a=[ ...new Set( oResults ) ];// create an array of unique elements using the `splat` operator and `Set`
                    if( oResults.length==2 ) b=a.length==2; // to be valid we need true & false in the array - hence a length of 2
                    if( oResults.length==2 )indicate( b ); // let user know selection is valid / invalid
                    return b;
                };
                const indicate=function(status){
                    [oPick,oDrop].forEach(el=>{
                        el.className=status ? 'ok' : 'bogus'
                    })
                };
                
                
                new google.maps.places.Autocomplete( oPick ).addListener('place_changed',changehandler);
                new google.maps.places.Autocomplete( oDrop ).addListener('place_changed',changehandler);
            }
        </script>
        <script async defer src='//maps.googleapis.com/maps/api/js?key=apikey&callback=initMap&libraries=places'></script>
    </head>
    <body>
        <div id='map'></div>
        <form>
            <label>Collect from:<input type='text' name='pick' /></label>
            <label>Deliver to:<input type='text' name='drop' /></label>
        </form>
    </body>
</html>