Loading of JS API
The JS API 2.0 Load via <script> tag
To avoid page operation errors caused by mismatches between map data protocol and front-end resources, only online loading of JS API is allowed, and local storage, mixing with other codes, and other usage are prohibited.
1、<script> tag loads JS API script
1.1 synchronous loading
<script> tag loads JS API 2.0
<!-- Need to set the width and height style of the element -->
<div id="container"></div>
<script type="text/javascript">
window._AMapSecurityConfig = {
securityJsCode: "「The security key you applied for」",
};
window._AMapServiceConfig = {
type: 'oversea', // Deployment Environment Setup
};
</script>
<script
type="text/javascript"
src=""https://sg-webapi.opnavi.com/maps?v=2.0&key=The key value you applied for"
></script>
<script type="text/javascript">
//Map initialization should occur after the map container <div> has been added to the DOM tree
var map = new AMap.Map("container", {
zoom: 12,
showOversea: true, //Enable world Map
});
</script>1.2 asynchronous loading
Asynchronous loading refers to the method of adding the JS API's <script> tag to the page through appendChild(), or adding the async attribute to the <script> tag. In this usage scenario, the JS API will not block the execution and parsing of other content on the page, but the script parsing of the JS API may occur after the execution of other script resources, so special handling is required to ensure that the relevant interfaces of the JS API are called after the AMap object is fully generated, otherwise it may cause errors.
The declaration of asynchronous callback functions should be before the introduction of the JS API.
UseappendChild():
<script>
//Set your security key
window._AMapSecurityConfig = {
securityJsCode: "「The security key you applied for」",
};
window._AMapServiceConfig = {
type: 'oversea', // Deployment Environment Setup
};
//Declare asynchronous loading callback function
window.onLoad = function () {
var map = new AMap.Map("container"); //"container" The id for the <div> container
};
var url ="https://sg-webapi.opnavi.com/maps?v=2.0&key=The key value you applied for&callback=onLoad";
var jsapi = document.createElement("script");
jsapi.charset = "utf-8";
jsapi.src = url;
document.head.appendChild(jsapi);
</script>Use the async attribute:
<script type="text/javascript"> //Declare asynchronous load callback function
//Set your security key
window._AMapSecurityConfig = {
securityJsCode: "「The security key you applied for」",
};
window._AMapServiceConfig = {
type: 'oversea', // Deployment Environment Setup
};
window.onLoad = function () {
var map = new AMap.Map("container");
};
</script>
<script
src="https://sg-webapi.opnavi.com/maps?v=2.0&key=The key value you applied for&callback=onLoad"
async="async"
type="text/javascript"
></script>