title: How can I get precise location with google maps api?
body: <p>I'm trying to show the user's current location on map. Using the HTML5 geolocation it asks the user for permission, which I find annoying and I found I could bypass this by using directly the google maps api.</p>
  
  <p>The problem is that with either solution the accuracy can be well off (300km off).</p>
  
  <h1>HTML5 solution</h1>
  
  <p><a href="https://developers.google.com/maps/documentation/javascript/geolocation" rel="nofollow noreferrer">https://developers.google.com/maps/documentation/javascript/geolocation</a></p>
  
  <p>This is the example that google provides and it is well off. Also the accuracy changes from browser to browser.</p>
  
  <h1>Google maps api solution</h1>
  
  <p>This is the code I've reached to.</p>
  
  <pre><code>function calculateZoomLevel(accuracy) {
      var equatorLength = 40075004; // in meters
      var mapWidth = 480; // in pixels
      var metersPerPixel = equatorLength / 4096;
      var zoomLevel = 1;
      while ((metersPerPixel * mapWidth) &gt; accuracy) {
          metersPerPixel /= 2;
          zoomLevel++;
      }
      return Math.min(zoomLevel, 17);
  }
  function initMap() {
      var coords = new google.maps.LatLng(37.990832, 23.70332), accuracy = 0;
      $.post('https://www.googleapis.com/geolocation/v1/geolocate?key=MY_API_KEY').done(function(e) {
          coords = new google.maps.LatLng(e.location.lat, e.location.lng);
          accuracy = e.accuracy;
          map = new google.maps.Map(document.getElementById('map'), {
              zoom: calculateZoomLevel(accuracy),
              center: coords,
              mapTypeId: google.maps.MapTypeId.ROADMAP,
          });
          new google.maps.Circle({
              center: coords,
              radius: accuracy,
              map: map,
              fillColor: '#ff0000',
              fillOpacity: .5,
              strokeColor: '#ff0000',
              strokeOpacity: .5
          });
      }).fail(function(e) {
          console.log('fail ajax post geolocation', e);
      });
  }
  </code></pre>
  
  <p>The thing is, I know the precision can be quite good (10-30 meters), since at the same time and on the same browser I see myself somewhere totally off on google's example, I see myself at my spot in the normal google maps page.</p>