我是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>
非常感谢任何帮助
----------------更新-------------------
Matt感谢你帮助到目前为止,我现在已经编辑了代码以将值输出到段落标签并删除了警告框,但它仍然不会显示lat和long,我的地理编码是否正确?它通过后置代码但不是lat和long或错误。
<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>
答案 0 :(得分:0)
我不是百分之百确定你正在做什么,因为你说你正在使用API的v3,但你不需要为v3构建google.maps.geocoder - 这是版本2的事情。除此之外,您甚至不会将Google的Javascript包含在<script>
标记的页面上。看看你的Javascript控制台。这可能会引发错误。
要使用v3进行地理编码,只需向此网址发出请求,例如:
响应是准备解析的JSON。不需要课程,实例化等。
这是你想要做的吗?