使 JavaScript Google API 地理编码发生在鼠标点击而不是页面加载上

Posted

技术标签:

【中文标题】使 JavaScript Google API 地理编码发生在鼠标点击而不是页面加载上【英文标题】:Make JavaScript Google API geocode happen on mouseclick instead of page load 【发布时间】:2017-09-21 18:38:50 【问题描述】:

我希望此脚本在单击鼠标单击而不是在页面加载时运行。

这是原始代码(在此处找到:Get city name using geolocation):

<!DOCTYPE html> 
<html> 
<head> 
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
<title>Reverse Geocoding</title> 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=[YOUR KEY HERE]"></script> 
<script type="text/javascript"> 
var geocoder;

if (navigator.geolocation) 
  navigator.geolocation.getCurrentPosition(successFunction, errorFunction);

// Get the latitude and the longitude;
function successFunction(position) 
  var lat = position.coords.latitude;
  var lng = position.coords.longitude;
  codeLatLng(lat, lng);


function errorFunction() 
  alert("Geocoder failed");


function initialize() 
  geocoder = new google.maps.Geocoder();



function codeLatLng(lat, lng) 
  var latlng = new google.maps.LatLng(lat, lng);
  geocoder.geocode(latLng: latlng, function(results, status) 
    if (status == google.maps.GeocoderStatus.OK) 
      if (results[1]) 
        var arrAddress = results;
        console.log(results);
        $.each(arrAddress, function(i, address_component) 
          if (address_component.types[0] == "locality") 
            console.log("City: " + address_component.address_components[0].long_name);
            itemLocality = address_component.address_components[0].long_name;
          
        );
       else 
        alert("No results found");
      
     else 
      alert("Geocoder failed due to: " + status);
    
  );

</script> 
</head> 
<body onload="initialize()"> 

</body> 
</html>

如果我将 &lt;body onload="initialize()"&gt; 更改为 &lt;a href="" onClick="initialize();"&gt;Get position&lt;/a&gt;我得到一个:

未捕获的类型错误:无法读取属性 'geocode' 不明确的 在代码LatLng 在成功函数

【问题讨论】:

可能是因为事情的执行顺序,试着把所有东西都放在一个函数中,甚至是变量声明,然后在点击时调用该函数 【参考方案1】:

工作代码

<!DOCTYPE html>
<html>

<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>Reverse Geocoding</title>
    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>

    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
        var geocoder;
        if (navigator.geolocation) 
            navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
        
        // Get the latitude and the longitude;
        function successFunction(position) 
            var lat = position.coords.latitude;
            var lng = position.coords.longitude;
            codeLatLng(lat, lng);
        

        function errorFunction() 
            alert("Geocoder failed");
        


        function codeLatLng(lat, lng) 
            geocoder = new google.maps.Geocoder();
            var latlng = new google.maps.LatLng(lat, lng);
            geocoder.geocode(
                latLng: latlng
            , function(results, status) 
                if (status == google.maps.GeocoderStatus.OK) 
                    if (results[1]) 
                        var arrAddress = results;
                        console.log(results);
                        $.each(arrAddress, function(i, address_component) 
                            if (address_component.types[0] == "locality") 
                                console.log("City: " + address_component.address_components[0].long_name);
                                itemLocality = address_component.address_components[0].long_name;
                            
                        );
                     else 
                        alert("No results found");
                    
                 else 
                    alert("Geocoder failed due to: " + status);
                
            );
        
    </script>
</head>

<body>
    <a href="" onClick="initialize();">Get position</a>
</body>

</html>

【讨论】:

抱歉,但这也会在页面加载时加载脚本。不只是为了我的 onClick。【参考方案2】:

如果查询集 get_location 设置为 true,则最终加载 navigator.geolocation.getCurrentPosition(successFunction, errorFunction);。作品。如果有人找到其他解决方案,请告诉我。

<!DOCTYPE html> 
<html> 
<head> 
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
<title>Reverse Geocoding</title> 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=[YOUR KEY HERE]"></script> 
<script type="text/javascript">
var getUrlParameter = function getUrlParameter(sParam) 
  var sPageURL = decodeURIComponent(window.location.search.substring(1)),
      sURLVariables = sPageURL.split('&'),
      sParameterName,
      i;

  for (i = 0; i < sURLVariables.length; i++) 
      sParameterName = sURLVariables[i].split('=');

      if (sParameterName[0] === sParam) 
          return sParameterName[1] === undefined ? true : sParameterName[1];
      
  
;

var geocoder;
var getPosition = getUrlParameter('get_position');


if (navigator.geolocation && getPosition == "true") 
  navigator.geolocation.getCurrentPosition(successFunction, errorFunction);

// Get the latitude and the longitude;
function successFunction(position) 
  var lat = position.coords.latitude;
  var lng = position.coords.longitude;
  codeLatLng(lat, lng);


function errorFunction() 
  alert("Geocoder failed");


function initialize() 
  geocoder = new google.maps.Geocoder();



function codeLatLng(lat, lng) 
  var latlng = new google.maps.LatLng(lat, lng);
  geocoder.geocode(latLng: latlng, function(results, status) 
    if (status == google.maps.GeocoderStatus.OK) 
      if (results[1]) 
        var arrAddress = results;
        console.log(results);
        $.each(arrAddress, function(i, address_component) 
          if (address_component.types[0] == "locality") 
            console.log("City: " + address_component.address_components[0].long_name);
            itemLocality = address_component.address_components[0].long_name;
          
        );
       else 
        alert("No results found");
      
     else 
      alert("Geocoder failed due to: " + status);
    
  );

</script> 
</head> 
<body> 

<a href="/?get_position=true">Get position</a>

</body> 
</html>

【讨论】:

以上是关于使 JavaScript Google API 地理编码发生在鼠标点击而不是页面加载上的主要内容,如果未能解决你的问题,请参考以下文章

如何使Event DOM Listener适应Google Maps JavaScript API v3.35

Google Maps Javascript API V3 在移动/本机应用程序上找不到 404

我如何使Figma API与Google App脚本API一起使用?

使用 Google Translate API 翻译 PDF 文件

从 javascript 调用 Google 云打印/搜索 API

Angular Js 和 google api client.js (gapi)