Mike Gifford
Mike Gifford

Reputation: 661

How to best display HTML5 geolocation accuracy on a google map

I'd like to:

  1. gather the latitude, longitude and accuracy of a user using HTML5
  2. display that in a google map as a dot
  3. change the size of the dot and indeed scale of the map to reflect the accuracy of the position.

This should be possible, but I have yet to see anyone implement this.

Upvotes: 18

Views: 11892

Answers (2)

Saravana
Saravana

Reputation: 61

    var circle;

    function initialize() {
       // Create the map.
        var mapOptions = {
            zoom: 4,
            center: new google.maps.LatLng(37.09024, -95.712891),
            mapTypeId: google.maps.MapTypeId.TERRAIN
        };

        var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

        // Construct the circle for each value in citymap.
        // Note: We scale the area of the circle based on the population.
        var populationOptions = {
            strokeColor: '#FF0000',
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: '#FF0000',
            fillOpacity: 0.35,
            map: map,
            center: citymap[city].center,
            radius: Math.sqrt(citymap[city].population) * 100
        };
        // Add the circle for this city to the map.
        circle = new google.maps.Circle(populationOptions);
    }

Source: Google documentation

Upvotes: 1

Bryan Weaver
Bryan Weaver

Reputation: 4473

Should be possible. According to this article the HTML5 position object returns the accuracy property in meters.

The google map api has the ability to draw circles given a center point (lat, lng) and a radius in meters.

I am thinking something like this:

var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var accuracy = position.coords.accuracy;

var centerPosition = new google.maps.LatLng(latitude, longitude);

var marker = new google.maps.Marker({
   position: centerPosition,
   map: //your map,
   icon: //the dot icon
});

var circle = new google.maps.Circle({
    center: centerPosition,
    radius: accuracy,
    map: //your map,
    fillColor: //color,
    fillOpacity: //opacity from 0.0 to 1.0,
    strokeColor: //stroke color,
    strokeOpacity: //opacity from 0.0 to 1.0
});

//set the zoom level to the circle's size
map.fitBounds(circle.getBounds());

Upvotes: 24

Related Questions