问题
I have a page and im trying to add google map to it but it doesn't appear in the page, it has no errors in the console log but it doesn't appear in my page, here is my code:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD19cqU2rIzBHOPL_t8GhJJ9cmi-HNpULg"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
function initialize() {
var mapOptions = {
zoom: 15,
scrollwheel: false,
center: new google.maps.LatLng((31.993072, 35.862211))
};
var map = new google.maps.Map(document.getElementById('googleMap'),
mapOptions);
var marker = new google.maps.Marker({
position: map.getCenter(),
animation:google.maps.Animation.BOUNCE,
icon: 'img/map-marker.png',
map: map
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
回答1:
Do with following
- add callback in src
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD19cqU2rIzBHOPL_t8GhJJ9cmi-HNpULg&callback=initialize"></script>
center:new google.maps.LatLng(31.993072, 35.862211)
instead ofcenter: new google.maps.LatLng((31.993072, 35.862211))
remove extra round bracket
function initialize() {
var mapOptions = {
zoom: 15,
scrollwheel: false,
center: new google.maps.LatLng(31.993072, 35.862211)
};
var map = new google.maps.Map(document.getElementById('googleMap'),
mapOptions);
var marker = new google.maps.Marker({
position: map.getCenter(),
animation: google.maps.Animation.BOUNCE,
//icon: 'img/map-marker.png',
map: map
});
}
#googleMap {
height: 400px;
width: 100%;
}
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD19cqU2rIzBHOPL_t8GhJJ9cmi-HNpULg&callback=initialize"></script>
<div id="googleMap">
</div>
回答2:
Please note that the particular key for google map only works for the specific domain, so if you are running on localhost, it won't display a map normally.
回答3:
Use iframe to show map in your website:
<iframe width="600" height="450" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/place?key=YOUR_API_KEY
&q=Space+Needle,Seattle+WA" allowfullscreen>
Google Maps Embed API Link
来源:https://stackoverflow.com/questions/43231277/adding-google-maps-to-my-website