Reputation: 17393
I want to use google map to get current lat and lon of user:
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCfbbmUkl56UuSeZ5nSOwsKTNxplmnheuU&callback=initialize&language=en" async defer></script>
the user should change the marker and I get new lat and lon.
is it possible to do that?
Upvotes: 0
Views: 2253
Reputation: 522
Code snippet that automatically detect user location by Using HTML Geolocation method. Make sure your browser enable location when you run this application and provide proper google map API link and most impotent the API key. Here is link of MDN Using geolocation where you can find detailed about geolocation and browser support information.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Click Me to show Your Location.</button>
<div id="map" style="width:100%;height:500px"></div>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var myCenter = new google.maps.LatLng(lat, lng);
var mapCanvas = document.getElementById("map");
var mapOptions = {
center: myCenter,
zoom: 5
};
var map = new google.maps.Map(mapCanvas, mapOptions);
var marker = new google.maps.Marker({
position: myCenter
});
marker.setMap(map);
// Zoom to 9 when clicking on marker
google.maps.event.addListener(marker, 'click', function () {
map.setZoom(9);
map.setCenter(marker.getPosition());
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU&callback=myMap"></script>
</body>
</html>
Hope this will help you
Upvotes: 3