[英]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.