I have the following piece of code which displays a map when the user clicks on the submit button.
At the moment the function initialize() takes no parameters and the map centers on a fixed latitude and longitude. I would like to be able to have latitude and longitude as parameters so that the map centers on those.
I have the latitude and the longitude already so getting these parameters isn't the problem; my problem is that I don't know how to pass them to the function.
Full code:
<!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>
JavaScript alone:
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);
}