在下面的代码中,
<head>
<title>Geo location</title>
<meta charset="UTF-8">
<script src="http://maps.googleapis.com/maps/api/js" type="text/javascript">
function showLocation(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition);
}else{
alert('geo location is not supported');
}
}
function showPosition(position){
console.log(Object.prototype.toString.call(position));
var mapProp = {
center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
</script>
</head>
<body>
<p> Click below to get your geo location</p>
<button onclick="showLocation();">Click</button>
<div id="googleMap" style="width:500px;height:380px;border: 1px solid red;"></div>
</body>
根据调试,单击事件
时出现错误showLocation
未定义
showLocation
在onclick
事件发生之前加载。
如何解决此错误?
答案 0 :(得分:1)
<script src="http://maps.googleapis.com/maps/api/js" type="text/javascript">
// all this will be ignored as the script tag has a src attribute
function showLocation(){
...
}
function showPosition(position){
...
}
</script>
试试这个
<script src="http://maps.googleapis.com/maps/api/js" type="text/javascript"></script>
<script type="text/javascript"></script>
function showLocation(){
...
}
function showPosition(position){
...
}
</script>
答案 1 :(得分:0)
此
没有结束标记<script src="http://maps.googleapis.com/maps/api/js" type="text/javascript">
必须是
<script src="http://maps.googleapis.com/maps/api/js" type="text/javascript"></script>
将其余的js代码放在另一个script
标记
CHECK HERE。控制台中没有错误。
答案 2 :(得分:0)
在关闭正文标记之前添加此脚本标记,您应该没问题。像这样:
<body>
...
<script>
function showLocation(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition);
}else{
alert('geo location is not supported');
}
}
function showPosition(position){
console.log(Object.prototype.toString.call(position));
var mapProp = {
center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
</script>
<body>
&#13;