gpt4 book ai didi

javascript - 使用 Google map API 和 Google 文本搜索进行地理定位

转载 作者:行者123 更新时间:2023-11-28 00:33:43 25 4
gpt4 key购买 nike

我是从 VB 转换 javascript 的新手。这是我第一次尝试创建动态谷歌地图,并最终尝试使用用户位置生成谷歌地图并应用体育商店的地点搜索。目前,我的 map 会生成并缩放到我的位置,但不会应用带有标记的搜索结果。这是我的代码:

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

<article>
<p>Finding your location: <span id="status">checking...</span></p>
</article>
<script>
function success(position) {
var s = document.querySelector('#status');

if (s.className == 'success') {
// not sure why we're hitting this twice in FF, I think it's to do with a cached result coming back
return;
}

s.innerHTML = "found you!";
s.className = 'success';

var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcanvas';
mapcanvas.style.height = '400px';
mapcanvas.style.width = '560px';

document.querySelector('article').appendChild(mapcanvas);



var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeControl: false,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);
var service;
var infowindow;
var request = {
location: latlng,
radius: '3200',
query: 'sports'
};

service = new google.maps.places.PlacesService(map);
service.textSearch(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]);
}
}
}
}

function error(msg) {
var s = document.querySelector('#status');
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';

// console.log(arguments);
}

if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
error('not supported');
}

</script>

我觉得我可能缺少一些变量分配或者没有从“ map Canvas ”中重写当前 map 。有没有人创建过类似的东西来提供一些见解?非常感谢任何帮助来查找为什么我的搜索结果不会显示在 map 上。谢谢!

最佳答案

您的代码可以运行,但缺少 createMarker 函数。这不是 API 方法。

Uncaught ReferenceError: createMarker is not defined

createMarker 函数示例:

function createMarker(place) {

new google.maps.Marker({
position: place.geometry.location,
map: map
});
}

注意:如果您只需要该函数中的位置,您也可以这样调用并修改它:

function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
console.log(place);
createMarker(results[i].geometry.location); // pass only the location to createMarker
}
}
}

function createMarker(position) {

new google.maps.Marker({
position: position,
map: map
});
}

JSFiddle demo

关于javascript - 使用 Google map API 和 Google 文本搜索进行地理定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28706144/

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