Javascript 尝试初始化Google地图时出错(代码=SCRIPT5009)

Javascript 尝试初始化Google地图时出错(代码=SCRIPT5009),javascript,google-maps,google-maps-api-3,Javascript,Google Maps,Google Maps Api 3,我正在尝试开发一个web移动应用程序,允许人们在不同的POI之间导航,但是我在尝试实现Google Maps Api时遇到了一个错误 以下是相关人员的代码: <!doctype html> <html> <head> <meta charset="utf-8"> <title>Mobile_Map_Application</title> <style type="text/css"> html, body{ he

我正在尝试开发一个web移动应用程序,允许人们在不同的POI之间导航,但是我在尝试实现Google Maps Api时遇到了一个错误

以下是相关人员的代码:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Mobile_Map_Application</title>
<style type="text/css">
html, body{ height: 100%; width: 100%; margin: 0; padding: 0; }
#map{height:100%;}
</style>
<script>
var map;
function initialise(){
map = new google.maps.Map( document.getElementById( 'map' ), {
zoom: 17,
center: { lat: 51.887082, lng:  -2.088722 }
} );
initialise();
</script>
<script type="text/javascript"src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&callback=initialise" async defer>
</script>
</head>

移动地图应用程序
html,正文{高度:100%;宽度:100%;边距:0;填充:0;}
#地图{高度:100%;}
var映射;
函数初始化(){
map=new google.maps.map(document.getElementById('map'){
缩放:17,
中心:{lat:51.887082,液化天然气:-2.088722}
} );
初始化();
我得到以下错误:

SCRIPT5009:“google”未定义

如何解决此问题?

问题 您的
initialise()
函数还不知道
google
对象,因为
google
对象只有在加载google API脚本后才知道


解决方案 解决此问题的最简单方法是:

  • initialise()
    函数的代码放在Google API脚本的
    script
    标记之后
  • 从Google API脚本的
    脚本
    标记中删除
    异步延迟
  • 另外:

  • 您在
    initialise()
    函数的末尾还缺少一个
    }

  • 您需要一个id为
    map
    的HTML元素才能使代码正常工作


  • 工作代码
    查看如何修复您的代码

    您正在调用
    initialise()在代码中执行一次,但这可能会在GoogleMapsJS加载之前执行

    您还可以在中指定
    initialise
    作为回调函数

    <script 
        type="text/javascript" 
        src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&callback=initialise" async defer>
    
    
    
    加载Maps JS后,这将执行
    初始化
    功能。这就是你所需要的;删除
    初始化()您在自己的JS中拥有的行

    注:约翰的回答指出了你需要做的几件事

    • 在函数末尾需要一个结束符
      }
    • 您需要在页面中输入
    PPS:加载Maps API时,不再需要指定
    sensor=false
    参数