简体   繁体   中英

Create Element to insert an API

I want to create a div using javascript to put my google map into. It creates a div, but doesnt put the map api into it. Please help.

You need to make sure the Google Maps API script has loaded before running your code. Currently, you are trying to build the map before the browser has downloaded the map API.

The simplest way to fix this is to change your HTML to this:

<script src="https://maps.googleapis.com/maps/api/js?key="Entered key here deleted it for stackoverflow"&callback=initMap">
<script src="javascript.js"></script>

You could also remove the Google Maps script tag and load it dynamically in javascript.js using jQuery's $.getScript() or with plain JS using https://github.com/filamentgroup/loadJS , running your code as the callback.

initMap is firing when the script loads, but create isn't getting called until you click that p tag. Here's a way to get around that issue, but still wait for the script to load before allowing clicks:

 var mapready = false, createcalled = false; function create() { createcalled = true; if(mapready){ var newDiv = document.createElement("map"); newDiv.id = "map"; newDiv.style.border="solid"; document.body.appendChild(newDiv); var uluru = {lat: 54.278556, lng: -8.460095}; var map = new google.maps.Map(document.getElementById('map'), {zoom: 16,center: uluru}); var marker = new google.maps.Marker({position: uluru,map: map}); } } function initMap() { mapready = true; if(createcalled) create(); } 

In this scenario, if the user clicks the p tag before the map is ready, the create function will fire as soon as the map API finishes loading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM