I'm trying to use geolocation. I'm using HTML
and javascript
to do it. What I wanted to do is after getting the user's location it will open a new tab that will go to google maps showing a direction. The start point is the user's location and the end point is already given. I used saddr
and daddr
in the google maps URL. I'm using Chrome browser to test and I already allowed to get my location.
Here is my code
For HTML
<span class="glyphicon glyphicon-road" id="getdir1" onclick="getLocation()" style="font-size:15px;"> Get Direction1</span>
<span class="glyphicon glyphicon-road" id="getdir2" onclick="getLocation()" style="font-size:15px;"> Get Direction2</span>
<span class="glyphicon glyphicon-road" id="getdir3" onclick="getLocation()" style="font-size:15px;"> Get Direction3</span>
<p id="geo-error"></p>
Here is my javascript LocationProvided is the address of my end point. I manually coded it.
<script>
var x = document.getElementById("geo-error");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var latlon = position.coords.latitude + "," + position.coords.longitude;
$("#getdir1").click() = function(){
window.open('http://maps.google.com/maps?saddr='+latlon+"&daddr=LocationProvided1");
}
$("#getdir2").click(function(){
window.open('http://maps.google.com/maps?saddr='+latlon+"&daddr=LocationProvided2");
});
$("#getdir3").click(function(){
window.open('http://maps.google.com/maps?saddr='+latlon+"&daddr=LocationProvided3");
});
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
</script>
My problem is when I click it for the first time it will open one window and when I click it again it will open two window that displays the location. I'm confuse why it opens two windows at the same time when I click it on the second time?