Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

谷歌地图 基础


创建基本谷歌地图

此示例创建了一个以英国伦敦为中心的谷歌地图

示例

<!DOCTYPE html>
<html>
<body>

<h1>我的第一个谷歌地图</h1>

<div id="googleMap" style="width:100%;height:400px;"></div>

<script>
function myMap() {
var mapProp= {
  center:new google.maps.LatLng(51.508742,-0.120850),
  zoom:5,
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&callback=myMap"></script>

</body>
</html>

本页面的其余部分将逐步描述上述示例。


地图容器和大小

地图需要一个 HTML 元素来容纳地图

<div id="googleMap" style="width:100%;height:400px"></div>

还要设置地图的大小。



创建函数以设置地图属性

function myMap() {
var mapProp = {
    center:new google.maps.LatLng(51.508742,-0.120850),
    zoom:5,
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
}

mapProp 变量定义了地图的属性。

center 属性指定地图的中心位置(使用经纬度坐标)。

zoom 属性指定地图的缩放级别(尝试用不同的缩放级别进行实验)。

代码行:var map=new google.maps.Map(document.getElementById("googleMap"), mapProp); 在 id 为“googleMap”的 <div> 元素内创建了一个新地图,并使用传递的参数(mapProp)。


多个地图

以下示例定义了四个具有不同地图类型的地图

示例

var map1 = new google.maps.Map(document.getElementById("googleMap1"), mapOptions1);
var map2 = new google.maps.Map(document.getElementById("googleMap2"), mapOptions2);
var map3 = new google.maps.Map(document.getElementById("googleMap3"), mapOptions3);
var map4 = new google.maps.Map(document.getElementById("googleMap4"), mapOptions4);

免费谷歌 API 密钥

谷歌允许网站每天免费调用任何谷歌 API 数千次。

访问 https://developers.google.com/maps/documentation/javascript/get-api-key 以了解如何获取 API 密钥。

谷歌地图希望在加载 API 时在 key 参数中找到 API 密钥

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&callback=myMap"></script>

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.