我有一个名为update details
的按钮。点击按钮后会创建一个包含3个标签的对话框。在第三个标签中,有一个名为map的字段,用户可以在那里选择他们在地图中的位置。我有2个隐藏包含存储在数据库中的用户的纬度和经度的字段。如果值为null,我需要将标记显示到它们的当前位置。我的代码如下。
<script>
$(document).ready(function(){
var directionsDisplay,
directionsService,
map;
$("#tabs").tabs({
show: function(e, ui) {
if (ui.index == 2) {
google.maps.event.trigger(map, "resize");//for showing google
//map in tabs
}
}
});
if(!window.google||!window.google.maps){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3&' +
'callback=initialize';
document.body.appendChild(script);
}
else{
initialize();
}
});
</script>
<script>
//var directionsDisplay,
//directionsService,
//map;
function initialize() {
//var directionsService = new google.maps.DirectionsService();
//directionsDisplay = new google.maps.DirectionsRenderer();
if(($("#latitude_val").val().length >3) || ($("#longitude_val").val().length>3))
{
var chicago = new google.maps.LatLng($("#latitude_val").val(), $("#longitude_val").val());
}
else
{
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': 'Dubai internet city'}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
console.log("Latitude: "+results[0].geometry.location.lat());
console.log("Longitude: "+results[0].geometry.location.lng());
}
else
{
console.log("Geocode was not successful for the following reason: " + status);
}
//console.log("latitude"+position.coords.latitude+'longitude='+position.coords.longitude);
});
}
//chicago = new google.maps.LatLng(51.508742, -0.120850);
var mapOptions = { zoom:16, mapTypeId: google.maps.MapTypeId.ROADMAP, center: chicago }
map = new google.maps.Map(document.getElementById("googlemap"), mapOptions);
var marker=new google.maps.Marker({
position:chicago,
map:map,
draggable:true,
animation: google.maps.Animation.DROP
});
marker.setMap(map);
google.maps.event.addListener(
marker,
'drag',
function() {
document.getElementById('latitude_val').value = marker.position.lat();
document.getElementById('longitude_val').value = marker.position.lng();
console.log($("#latitude_val").val());
console.log($("#longitude_val").val());
}
);
//directionsDisplay.setMap(map);
}
function fail(){
alert('navigator.geolocation failed, may not be supported');
}
</script>
当我运行此代码时,它显示以下错误。
ReferenceError: google is not defined
google.maps.event.trigger(map, "resize");
答案 0 :(得分:1)
在您添加加载Google地图javascript的调用之前,您正在调用google.maps.event.trigger
。也许只是交换文档中正在发生的事情的两个部分。已经
$(document).ready(function(){
var directionsDisplay,
directionsService,
map;
if(!window.google||!window.google.maps){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3&' +
'callback=initialize';
document.body.appendChild(script);
}
else{
initialize();
}
$("#tabs").tabs({
show: function(e, ui) {
if (ui.index == 2) {
google.maps.event.trigger(map, "resize");//for showing google
//map in tabs
}
}
});
});