gpt4 book ai didi

javascript - map 未显示在网页上(Google map /地点 API)

转载 作者:行者123 更新时间:2023-12-03 11:34:28 26 4
gpt4 key购买 nike

这是我的第一个 HTML/Javascript 项目,我遇到了一些麻烦。目标是获取一个地址,并简单地显示一张带有该地址 500m 范围内商店标记的 map 。问题是我得到一个空白页;什么也没有出现。大部分代码都是从 Google 的示例中逐字复制的,因此我不知道可能出了什么问题。

HTML:

<!DOCTYPE html>
<html>
<head>
<title>Make a Good Impression</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=myKeyGoesHere"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<script type="text/javascript" src="coffee_and_donuts.js"></script>
</head>
<body>
<div id="map" style="float:left;width:30%;height 100%"></div>
</body>
</html>

coffee_and_donuts.js:

var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var geocoder = new google.maps.Geocoder();
var DESTINATION_ADDRESS = "New York, New York";
var destination_LatLng;


// get the destination's LatLng object
geocoder.geocode( {'address': DESTINATION_ADDRESS}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
destination_LatLng = results[0].geometry.location;
}
});


// feed the destination's LatLng object to the places API to find the nearest stores

var map;
var service;
var infowindow;

function initialize2() {
map = new google.maps.Map(document.getElementById('map'), {
center: destination_LatLng,
zoom: 15
});

var request = {
location: destination_LatLng,
radius: '500',
types: ['store']
};

service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}

function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}

initialize2();

最佳答案

您需要从地理编码函数回调中调用initialize2();:

// get the destination's LatLng object
geocoder.geocode( {'address': DESTINATION_ADDRESS}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
destination_LatLng = results[0].geometry.location;
initialize2();
}
});

问题是您试图在地理编码器完成之前初始化 map 。

您还可以将所有内容放在一个链接中:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places"></script> 

关于javascript - map 未显示在网页上(Google map /地点 API),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26579321/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com