我目前正在使用谷歌地图并使用地理位置绘制人员位置。我使用了google示例中的代码,该代码允许使用nogeolocation响应,它基本上要求一组硬编码的坐标。我想要做的是有一个带有城市列表的选择框的js模态弹出窗口。当选择其中一个城市时,地图将填充到该城市。我有一个城市列表,与它们相关的值是坐标。我相信我使用当前代码时遇到的问题是它是在通过下拉框设置之前跳过变量。
的.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>
答案 0 :(得分:2)
您正在更改事件函数中创建一个变量,然后尝试在它之外使用它,它在那里不可见。虽然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);
});