[英]Unable to load google map while using jquery
如果我不在 head 标签中包含 jquery.min.js,地图加载成功。 如果我包含它给我initMap :没有这样的方法错误。 如果我颠倒包含顺序:首先映射然后是 jquery,则 initMap 方法永远不会被回调并且不会加载 map。 如果我在 document.ready 中调用 initMap,它会给我 ReferenceError: google is not defined。
我如何找到一种在同一页面中同时使用 Maps 和 jquery 的方法。
<!DOCTYPE html>
<html>
<head>
<title>maps test</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"/>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBEn8E0rL_XdVl2WDLAwgjpM62AM2QoRXI&v=3.exp&sensor=false&libraries=places&callback=initMap"
async defer></script>
</head>
<body>${message}<br>
<input id="location" type="text" value="Enter your location"/><br>
<select id="activity" value=" activity">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<div id="map"></div>
<script>
var map;
var autocomplete;
var globalData;
$(document).ready(function(){
initMap();
});
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
initialize();
}
function initialize() {
autocomplete = new google.maps.places.Autocomplete(
/** @type {HTMLInputElement} */(document.getElementById('location')),
{ types: ['geocode'] });
google.maps.event.addListener(autocomplete, 'place_changed', loadMarkers);
}
function loadMarkers(){
var place = autocomplete.getPlace();
var loc = place.geometry.location;
var address = place.address_components;
$.ajax({
type: "POST",
dataType: "json",
data: {loc : loc, address : address},
url: '/getmarkers.do',
success: function(data) {
globalData = data;
// get array of latlng
// create marker
}
});
}
</script>
</body>
</html>
您用于包含 JQuery 的脚本标记不正确:
这个:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"/>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBEn8E0rL_XdVl2WDLAwgjpM62AM2QoRXI&v=3.exp&sensor=false&libraries=places&callback=initMap"
async defer></script>
应该是(注意/>
变成了></script>
:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBEn8E0rL_XdVl2WDLAwgjpM62AM2QoRXI&v=3.exp&sensor=false&libraries=places&callback=initMap"
async defer></script>
脚本标签必须是<script></script>
。
在jQuery
准备好后尝试加载google map api
。
一切正常,您只是错过了jquery 脚本的 Closing 标记,即</script>
。 关闭脚本,它工作正常。
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"/></script>
将此添加到您的代码中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.