function showPosition() {
navigator.geolocation.getCurrentPosition(showMap, error);
}
function showMap(position) {
// Get location data
var mylatlong = position.coords.latitude + "," + position.coords.longitude;
// Set Google map source url
var mapLink = "https://maps.googleapis.com/maps/api/staticmap?center=" + mylatlong + "&size=50x50";
// Create and insert Google map
document.getElementById("embedMap").innerHTML = "<img alt='Map Holder' src='" + mapLink + "'>";
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
<input type="button" value="Add Map" onclick="showPosition()" />
<div id="embedMap">
<!--Google map will be embedded here-->
</div>
I am new to Javascript and HTML and currently testing out how to get current location and show it in google map after clicking the button. I have tried this but I still cannot get my current location in a map.
app.js
function showPosition() {
navigator.geolocation.getCurrentPosition(showMap);
}
function showMap(position) {
// Get location data
var latlong = position.coords.latitude + "," + position.coords.longitude;
// Set Google map source url
var mapLink = "https://maps.googleapis.com/maps/api/staticmap?center="+latlong+"&zoom=16&size=400x300&output=embed";
// Create and insert Google map
document.getElementById("embedMap").innerHTML = "<img alt='Google map' src='"+ mapLink +"'>";
}
index.html
<input type="button" value="Add Map" onclick="showPosition()"/>
<div id="embedMap">
<!--Google map will be embedded here-->
</div>