我是 javascript 和地理编码的新手,我正在尝试学习如何将两者结合使用。
我创建了一个表单来获取用户输入的邮政编码,然后我有代码将其转换为 long 和 lat。我已经包含并提醒显示邮政编码,以便我知道有多少工作(更多帮助我自学)
它返回带有输入邮政编码的警报框,但没有别的!?
我希望它在警报框中显示长和纬度。一旦我知道我有 long 和 lat,我会考虑将它们添加到 MySQL 表中,但是一旦我知道我已经检索了这些值,我就会担心
这是代码:
<html>
<head>
<script type="text/javascript">
function getPostCode() {
var postcode = document.getElementById("pcode").value;
alert("Your Post Code is: " + postcode);
var gc = new google.maps.Geocoder();
gc.geocode({'address' : postcode}, function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
alert( "latitude : " + results[0].geometry.location.lat() );
alert( "longitude : " + results[0].geometry.location.lng() );
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body>
<form name="search" METHOD="GET" onsubmit="return getPostCode()">
Post Code: <input type="text" name="pcode" />
<input type="submit" value="Search"/>
</form>
</body>
</html>
任何帮助将非常感激
- - - - - - - - 更新 - - - - - - - - - -
马特感谢您到目前为止的帮助,我现在已经编辑了代码以将值输出到段落标签并删除了警告框,但它仍然不会显示经纬度,我的地理编码代码是否正确?它通过邮政编码而不是经纬度或错误。
<html>
<head>
<script type="text/javascript">
function getPostCode() {
var postcode = document.getElementById("pcode").value;
var postcode = "Your Post Code is: " + postcode;
document.getElementById("p1").innerHTML=postcode;
var mygc = new google.maps.Geocoder();
mygc.geocode({'address' : postcode}, function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat();
document.getElementById("lat").innerHTML=lat;
var lat = results[0].geometry.location.lng();
document.getElementById("long").innerHTML=long;
} else {
var err = "Geocode was not successful for the following reason: " + status;
document.getElementById("error").innerHTML=err;
}
});
}
</script>
</head>
<body>
<form name="search">
Post Code: <input type="text" name="pcode" />
<input type="button" value="Search" onclick="getPostCode()" />
</form>
<p id="p1"></p>
<p id="long"></p>
<p id="lat"></p>
<p id="error"></p>
</body>
</html>