简体   繁体   English

使用按钮单击而不是正文加载

[英]Using button click instead of body onload

I'm attempting to use the Google geocoder API to enter user's location information directly into a form (reverse geocoding). 我正在尝试使用Google地理编码器API将用户的位置信息直接输入表单(反向地理编码)。 I am using the most popular answer in this post as a code base. 我使用这篇文章中最受欢迎的答案作为代码库。

My form is correctly populated when I use body onload="initialize()" as shown in that answer. 当我使用body onload =“ initialize()”时,正确填写了我的表单,如该答案所示。 However when I attempt to initiate the function using a button nothing happens (I remove the body onload attribute). 但是,当我尝试使用按钮启动功能时,什么也没发生(我删除了主体的onload属性)。 I have tried the following two variations. 我尝试了以下两种变体。

<a href="javascript:;" style="center" onclick="initiate()" class="button">Get Geolocation data</a>

<input type="button" value="Get Geolocation Data" onclick="initiate()">

Could someone please point out my mistake? 有人可以指出我的错误吗? Full code is as follows: 完整代码如下:

    <!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 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 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) {
      console.log(results)
        if (results[1]) {
         //formatted address
         alert(results[0].formatted_address)
        //find country name
             for (var i=0; i<results[0].address_components.length; i++) {
            for (var b=0;b<results[0].address_components[i].types.length;b++) {

            //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
                if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
                    //this is the object you are looking for
                    city= results[0].address_components[i];
                    break;
                }
            }
        }
        //city data
        alert(city.short_name + " " + city.long_name)


        } else {
          alert("No results found");
        }
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });
  }
</script> 
</head> 
<body onload="initialize()"> 

</body> 
</html> 

Many thanks in advance. 提前谢谢了。

Looks like a typo: use initialize instead of initiate . 看起来像一个错字:使用initialize ,而不是initiate

You state that you were using body onload="initialize()" , and when you moved the call to your initialize function to a button's onclick it stopped working. 您声明正在使用body onload="initialize()" ,并且当将对initialize函数的调用移到按钮的onclick时,它停止工作。

In your example however, you've used initiate : 但是,在您的示例中,您使用了initiate

<a href="javascript:;" style="center" onclick="initiate()" class="button">Get Geolocation data</a>

<input type="button" value="Get Geolocation Data" onclick="initiate()">

That is because you are using onlick on a anchor element without stopping its default behavior. 那是因为您在锚元素上使用onlick而不停止其默认行为。 Try this. 尝试这个。

<a href="#" style="center" onclick="return initialize()" class="button">Get Geolocation</a>

And return false from initialize js method. 并从initialize js方法返回false。

function initiate() {
   geocoder = new google.maps.Geocoder();
   return false;
}

As @Michael mentioned there is a typo as well. 正如@Michael提到的那样,还有一个错字。

Change this: 更改此:

<a href="javascript:;" style="center" onclick="initiate()" class="button">Get Geolocation data</a>

To this: 对此:

<a href="javascript:initiate();return(false);" style="center" class="button">Get Geolocation data</a>

And make sure whether your function is called initiate() or initialize() . 并确保你的函数是被称为启动()初始化()。 There seems to be a typo there. 那里似乎有错字。

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

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