Pau*_*ine 5 javascript google-maps callback
我有以下一段代码,当用户单击“提交”按钮时,它将显示一个地图。
目前,函数initialize()没有任何参数,并且地图以固定的纬度和经度为中心。我希望能够将纬度和经度作为参数,以便地图以此为中心。
我已经有了经度和纬度,因此获取这些参数不是问题;我的问题是我不知道如何将它们传递给函数。
完整代码:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
</head>
<body>
<div id="map">
<button type="button" onclick="loadScript()">submit</button>
</div>
<script>
function initialize() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
myOptions);
}
function loadScript() {
var myKey = "myAPIKey";
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "https://maps.googleapis.com/maps/api/js?key=" + myKey + "&sensor=false&callback=initialize";
document.body.appendChild(script);
}
</script>
</body>
Run Code Online (Sandbox Code Playgroud)
仅JavaScript:
function initialize() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
myOptions);
}
function loadScript() {
var myKey = "myAPIKey";
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "https://maps.googleapis.com/maps/api/js?key=" + myKey + "&sensor=false&callback=initialize";
document.body.appendChild(script);
}
Run Code Online (Sandbox Code Playgroud)
小智 4
只需在脚本之前启动变量即可。在“loadScript”函数中更新变量并在“initialize”函数中使用它们。对我来说,它有效。
<script>
var string = ""; // initialize variables here. You need var lat and var lng
function initialize() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
console.log(string); // just checking, if it does work in "initialize" function
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
myOptions);
}
function loadScript() {
var myKey = "myAPIKey";
var script = document.createElement('script');
script.type = 'text/javascript';
string = "hey it works"; //////////// here take the coordinates
script.src = "https://maps.googleapis.com/maps/api/js?&sensor=false&callback=initialize";
document.body.appendChild(script);
}
</script>
Run Code Online (Sandbox Code Playgroud)
另外,我认为稍后可以使用以下命令更改位置:
map.setCenter(new google.maps.LatLng( 45, 19 ) );
Run Code Online (Sandbox Code Playgroud)
我希望它有帮助
| 归档时间: |
|
| 查看次数: |
7948 次 |
| 最近记录: |