Google Maps API Javascript,从页面上的表单输入中获取经度纬度

我正在尝试创建一个 1 页地图生成器,他们在其中输入地址和邮政编码。


这部分有效


Geolocation API 然后进行反向查找以获取经度和纬度,并将其填充到 2 个隐藏的输入字段以供以后使用。


这部分不起作用


然后,我需要使用 Maps API 从隐藏的输入中获取经度和纬度值并生成地图,但是,变量为 NULL,因为它们设置在单击时激活的函数中。


我需要能够在设置值后触发地图生成器代码,或者最初从一组数字传递一组值,然后单击按钮使用隐藏值重新运行代码。


<script>

var apiKey='REMOVED FOR PRIVACY';

var longitude, latitude, map;


jQuery(document).ready(function( $ ) {

    $('#find-address').click(function () {

        var address = $('#address').val();

        var postcode = $('#postcode').val();

        var addressClean = address.replace(/\s+/g, '+');

        var postcodeClean = postcode.replace(/\s+/g, '+');

        var apiCall = 'https://maps.googleapis.com/maps/api/geocode/json?address='+addressClean+',+'+postcodeClean+'&key='+apiKey+'';


        $.getJSON(apiCall,function (data, textStatus) {

            longitude = data.results[0].geometry.location.lng;

            latitude = data.results[0].geometry.location.lat;

            document.getElementById("long").value = longitude;

            document.getElementById("lat").value = latitude;

        });


        setTimeout(function(){

            longitude = $("input#long").val();

            latitude = $("input#lat").val();


            if(longitude && latitude){

                longitude = parseFloat(longitude);

                latitude = parseFloat(latitude);


                initMap(longitude,latitude);

            }

        }, 1000);

    });

});


function initMap(longitude,latitude) {

    var myLatlng = new google.maps.LatLng(latitude,longitude);


    var mapOptions = {

      zoom: 12,

      center: myLatlng

    }


    var map = new google.maps.Map(document.getElementById("map-embed-div"), mapOptions);


    var marker = new google.maps.Marker({

        position: myLatlng,

        map: map,

        draggable: true,

        title: "Where's your garden?"

    });

};

</script>

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

我尝试在 setTimeout 函数中调用该函数并在函数回调中传递值,但这会返回 NULL。


在 timeout 函数中移动所有内容会引发未定义 initMap 的 promise 错误。


沧海一幻觉
浏览 310回答 1
1回答

牧羊人nacy

有几个问题。我收到 JavaScript 错误:InvalidValueError: setCenter: not a LatLng or LatLngLiteral with finite coordinates: in property lat: NaN is not an accepted value因为在您的 API 中包括:你有callback=initMap,但你不希望它在 API 加载时运行,你希望它在用户单击“查找地址”后运行。删除:<script&nbsp;src="https://maps.googleapis.com/maps/api/js?key=REMOVED_FOR_PRIVACY"&nbsp;async&nbsp;defer></script>我收到 JavaScript 错误:Uncaught TypeError: Cannot read property 'geometry' of undefined当我单击“查找地址”时,因为没有错误检查。如果我检查文本状态(至少使用 Google 测试键),它会告诉我:"API keys with referer restrictions cannot be used with this API.",&nbsp;status: "REQUEST_DENIED".&nbsp;如果我对地理编码器的请求使用不受限制的密钥,我会得到一个带有标记的地图(至少对于有效地址)。我建议使用 Google JavaScript API v3 Geocoder,并添加错误检查:var geocoder = new google.maps.Geocoder();geocoder.geocode({&nbsp; address: addressClean + "," + postcodeClean}, function(results, status) {&nbsp; console.log(status);&nbsp; if (status == 'OK') {&nbsp; &nbsp; console.log(results);&nbsp; &nbsp; longitude = results[0].geometry.location.lng();&nbsp; &nbsp; latitude = results[0].geometry.location.lat();&nbsp; &nbsp; document.getElementById("long").value = longitude;&nbsp; &nbsp; document.getElementById("lat").value = latitude;&nbsp; &nbsp; // geocoder is asynchronous, do this in the callback function&nbsp; &nbsp; longitude = $("input#long").val();&nbsp; &nbsp; latitude = $("input#lat").val();&nbsp; &nbsp; if (longitude && latitude) {&nbsp; &nbsp; &nbsp; longitude = parseFloat(longitude);&nbsp; &nbsp; &nbsp; latitude = parseFloat(latitude);&nbsp; &nbsp; &nbsp; initMap(longitude, latitude);&nbsp; &nbsp; }&nbsp; } else alert("geocode failed")});代码片段:var apiKey = 'AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk';var longitude, latitude, map;jQuery(document).ready(function($) {&nbsp; $('#find-address').click(function() {&nbsp; &nbsp; var address = $('#address').val();&nbsp; &nbsp; var postcode = $('#postcode').val();&nbsp; &nbsp; var addressClean = address.replace(/\s+/g, '+');&nbsp; &nbsp; var postcodeClean = postcode.replace(/\s+/g, '+');&nbsp; &nbsp; var apiCall = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + addressClean + ',+' + postcodeClean + '&key=' + apiKey + '';&nbsp; &nbsp; //$.getJSON(apiCall,function (data, textStatus) {&nbsp; &nbsp; var geocoder = new google.maps.Geocoder();&nbsp; &nbsp; geocoder.geocode({&nbsp; &nbsp; &nbsp; address: addressClean + "," + postcodeClean&nbsp; &nbsp; }, function(results, status) {&nbsp; &nbsp; &nbsp; console.log(status);&nbsp; &nbsp; &nbsp; if (status == 'OK') {&nbsp; &nbsp; &nbsp; &nbsp; console.log(results);&nbsp; &nbsp; &nbsp; &nbsp; longitude = results[0].geometry.location.lng();&nbsp; &nbsp; &nbsp; &nbsp; latitude = results[0].geometry.location.lat();&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("long").value = longitude;&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("lat").value = latitude;&nbsp; &nbsp; &nbsp; &nbsp; // geocoder is asynchronous, do this in the callback function&nbsp; &nbsp; &nbsp; &nbsp; longitude = $("input#long").val();&nbsp; &nbsp; &nbsp; &nbsp; latitude = $("input#lat").val();&nbsp; &nbsp; &nbsp; &nbsp; if (longitude && latitude) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; longitude = parseFloat(longitude);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; latitude = parseFloat(latitude);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; initMap(longitude, latitude);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; } else alert("geocode failed")&nbsp; &nbsp; });&nbsp; });&nbsp; function initMap(longitude, latitude) {&nbsp; &nbsp; var myLatlng = new google.maps.LatLng(latitude, longitude);&nbsp; &nbsp; var mapOptions = {&nbsp; &nbsp; &nbsp; zoom: 12,&nbsp; &nbsp; &nbsp; center: myLatlng&nbsp; &nbsp; }&nbsp; &nbsp; var map = new google.maps.Map(document.getElementById("map-embed-div"), mapOptions);&nbsp; &nbsp; var marker = new google.maps.Marker({&nbsp; &nbsp; &nbsp; position: myLatlng,&nbsp; &nbsp; &nbsp; map: map,&nbsp; &nbsp; &nbsp; draggable: true,&nbsp; &nbsp; &nbsp; title: "Where's your garden?"&nbsp; &nbsp; });&nbsp; };})/* Always set the map height explicitly to define the size of the div&nbsp;* element that contains the map. */#map {&nbsp; height: 100%;}/* Optional: Makes the sample page fill the window. */html,body {&nbsp; height: 100%;&nbsp; margin: 0;&nbsp; padding: 0;}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><form action="/instant-quote-test/#wpcf7-f3686-p3924-o1" method="post" class="wpcf7-form mailchimp-ext-0.5.14" novalidate="novalidate">&nbsp; <div style="display: none;">&nbsp; &nbsp; <input type="hidden" name="_wpcf7" value="3686" /><br />&nbsp; &nbsp; <input type="hidden" name="_wpcf7_version" value="5.1.7" /><br />&nbsp; &nbsp; <input type="hidden" name="_wpcf7_locale" value="en_GB" /><br />&nbsp; &nbsp; <input type="hidden" name="_wpcf7_unit_tag" value="wpcf7-f3686-p3924-o1" /><br />&nbsp; &nbsp; <input type="hidden" name="_wpcf7_container_post" value="3924" />&nbsp; </div>&nbsp; <p><span class="wpcf7-form-control-wrap your-fname"><input type="hidden" name="your-fname" value="" size="40" class="wpcf7-form-control wpcf7dtx-dynamictext wpcf7-dynamichidden" aria-invalid="false" /></span><span class="wpcf7-form-control-wrap your-email"><input type="hidden" name="your-email" value="" size="40" class="wpcf7-form-control wpcf7dtx-dynamictext wpcf7-dynamichidden" aria-invalid="false" /></span>&nbsp; &nbsp; <span&nbsp; &nbsp; &nbsp; class="wpcf7-form-control-wrap your-phone"><input type="hidden" name="your-phone" value="" size="40" class="wpcf7-form-control wpcf7dtx-dynamictext wpcf7-dynamichidden" aria-invalid="false" /></span>&nbsp; </p>&nbsp; <input type="text" name="street-address" value="77 Mass Ave" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" id="address" aria-required="true" aria-invalid="false" placeholder="Street Address" />&nbsp; <input type="text" name="post-code" value="02139" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" id="postcode" aria-required="true" aria-invalid="false" placeholder="Post Code" />&nbsp; <input type="hidden" id="lat" value=""><input type="hidden" id="long" value="">&nbsp; <input type="hidden" name="addressField1" value=""><input type="hidden" name="postcodeField">&nbsp; <a href="#" id="find-address" title="Find Address" class="button">Find Address</a>&nbsp; <div id="map-embed">&nbsp; &nbsp; <div id="map-embed-div" style="height:400px;width:100%;"></div>&nbsp; </div>&nbsp; <div id="after-map-quote">&nbsp; &nbsp; <input type="submit" value="Get My Lawn Care Quote" class="wpcf7-form-control wpcf7-submit quote-send" />&nbsp; </div></form><!-- Replace the value of the key parameter with your own API key. --><script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" async defer></script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript