我目前正在使用谷歌地图并使用地理定位绘制一个人的位置。我使用了谷歌示例中的代码,它允许非地理定位响应,它基本上要求一组硬编码的坐标。我想要做的是有一个带有带有城市列表的选择框的 js 模式弹出窗口。选择其中一个城市后, map 将填充到该城市。我有一个城市列表和与之相关的值有坐标。我相信我当前代码遇到的问题是它在能够通过下拉框设置之前跳过变量。
.js
function handleNoGeolocation(errorFlag) {
if(errorFlag == true) {
//alert("Geolocation service failed.");
$('#myModal').modal('show');
$('#citiesList').change(function(){
var location = $(this).val();
parseFloat(location);
});
initialLocation = new google.maps.LatLng(location);
} else {
alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
initialLocation = siberia;
}
map.setCenter(initialLocation);
}
.html
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<select id="citiesList" class="form-control">
<option value=''>Select City...</option>
<option value="53.5412083, -113.29573650">Sherwood Park</option>
<option value="51.04532,-114.058106">Calgary</option>
</select>
</div>
</div>
</div>
</div>
最佳答案
您正在更改事件函数中创建一个变量,然后尝试在它不可见的外部使用它。虽然 Javascript 是同步的,但此处并未触发更改事件,它只是被设置,因此当更改事件已触发时,handleNoGeolocation
中的代码已被执行。
$('#myModal').modal('show');
$('#citiesList').change(function(){
//creates a local scope variable 'location' visible only in this function
var location = $(this).val();
//note this isnt being used as you are not setting the result to anything
parseFloat(location);
});
//'location' here is undefined
initialLocation = new google.maps.LatLng(location);
在可以看到变量的更改函数中执行调用
编辑:
$('#myModal').modal('show');
$('#citiesList').change(function(){
var location = $(this).val();
//splits the string on ',', so we can use the lat lng separately
location = location.split(",");
//use $.trim to remove any of the whitespaces
initialLocation = new google.maps.LatLng($.trim(location[0]),$.trim(location[1]));
map.setCenter(initialLocation);
});
关于javascript - 谷歌地图上没有地理定位,如何询问人员位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21493661/