Shah Ankit
Shah Ankit

Reputation: 129

Google Map geolocation getcurrentposition()

I am using the google geolocation's getCurrentPosition() function for get the current position of the user.

It works fine for me in firefox but not working on chrome.

My code is as below ::

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>

<p id="demo">Click the button to get your position.</p>

<button onclick="getLocation()">Try It</button>

<div id="mapholder"></div>

<script>
var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, showtemp);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    var latlon = position.coords.latitude + "," + position.coords.longitude;

    var img_url = "http://maps.googleapis.com/maps/api/staticmap?center="
    +latlon+"&key=AIzaSyDOgvRydLLNrztjgagobYS_sROK1u3r4M4&zoom=14&size=400x300&sensor=false";
    document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}
function showtemp(temp) { 
    alert("test");
    }

function showError(error) {  

    $.get("http://ipinfo.io", function (response) {
        var array = (response.loc).split(',');
        console.log(array[0]);
        var latlon = array[0] + "," + array[1];
        var img_url = "http://maps.googleapis.com/maps/api/staticmap?center="
         +latlon+"&zoom=14&size=400x300&sensor=false";
            document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
     }, "jsonp");
} 
</script>

</body>
</html>

Please help me solve this.

It Gives me error :: " getCurrentPosition() and watchPosition() are deprecated on insecure origins, and support will be removed in the future. You should consider switching your application to a secure origin, such as HTTPS."

Thanks in advance

Upvotes: 1

Views: 2236

Answers (3)

Ben Dowling
Ben Dowling

Reputation: 17541

You could use the https://ipinfo.io API (it's my service) as an alternative to getCurrentLocation(). It's free for up to 1,000 req/day (with or without SSL support). It gives you coordinates, name and more, works on non-SSL sites, and doesn't prompt the user for permission. Here's an example:

curl ipinfo.io
{
  "ip": "172.56.39.47",
  "hostname": "No Hostname",
  "city": "Oakland",
  "region": "California",
  "country": "US",
  "loc": "37.7350,-122.2088",
  "org": "AS21928 T-Mobile USA, Inc.",
  "postal": "94621"
}

Here's an example which constructs a coords object with the API response that matches what you get from getCurrentPosition():

$.getJSON('https://ipinfo.io/geo', function(response) { 
    var loc = response.loc.split(',');
    var coords = {
        latitude: loc[0],
        longitude: loc[1]
    };
});

And here's a detailed example that shows how you can use it as a fallback for getCurrentPosition():

function do_something(coords) {
    // Do something with the coords here
}

navigator.geolocation.getCurrentPosition(function(position) { 
    do_something(position.coords);
    },
    function(failure) {
        $.getJSON('https://ipinfo.io/geo', function(response) { 
        var loc = response.loc.split(',');
        var coords = {
            latitude: loc[0],
            longitude: loc[1]
        };
        do_something(coords);
        });  
    };
});

See http://ipinfo.io/developers/replacing-navigator-geolocation-getcurrentposition for more details.

Upvotes: 0

geekonaut
geekonaut

Reputation: 5954

Geolocation is not deprecated per se, but limited to sites served via HTTPS.

The warning itself reads "getCurrentPosition() and watchPosition() are deprecated on insecure origins", which boilds down to pages served via HTTP and not HTTPS.

See, your code works fine here in the latest Chrome.

The easiest way to get SSL is probably to use Github pages for hosting your content or using something surge.

Upvotes: 0

Bhavin
Bhavin

Reputation: 2158

getcurrentposition() is deprected and there is no replacement of it. read this answer :- getcurrentposition-and-watchposition-are-deprecated-on-insec‌​ure-origins

Click on this google updated api's example link it's working example. : https://developers.google.com/maps/documentation/javascript/examples/map-geolocation.

Hover at top right of the code block to copy the code or open it in JSFiddle.

Use this functions :

// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.

<script>
    function initMap() {
      var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: -34.397, lng: 150.644},
        zoom: 6
      });
      var infoWindow = new google.maps.InfoWindow({map: map});

      // Try HTML5 geolocation.
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          var pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
          };

          infoWindow.setPosition(pos);
          infoWindow.setContent('Location found.');
          map.setCenter(pos);
        }, function() {
          handleLocationError(true, infoWindow, map.getCenter());
        });
      } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
      }
    }

    function handleLocationError(browserHasGeolocation, infoWindow, pos) {
      infoWindow.setPosition(pos);
      infoWindow.setContent(browserHasGeolocation ?
                            'Error: The Geolocation service failed.' :
                            'Error: Your browser doesn\'t support geolocation.');
    }

</script>

Upvotes: 1

Related Questions