index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Location API</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
</head>
<body>
<style>
body {
margin: 0;
}
svg {
background-color: #333;
cursor: pointer;
}
.land {
fill: #00D9FF;
fill-opacity: 0.35;
stroke: #00D9FF;
stroke-width: 1;
}
.location {
fill: none;
stroke: #FFFB00;
stroke-width: 2;
}
.coords {
fill: none;
stroke: #FFFB00;
font-family: 'Helvetica Neue', Helvetica, sans-serif;
font-weight: 300;
font-size: 16px;
}
</style>
<div id="map-container"></div>
<script>
var width = 960,
height = 480;
var div = d3.select('#map-container'),
svg = div.append('svg');
svg.attr('width', width).attr('height', height);
var projection = d3.geo.equirectangular()
.translate([width / 2, height / 2]);
var pathGenerator = d3.geo.path()
.projection(projection);
d3.json('land.geojson', function(err, data) {
if (err) { throw err; }
var land = svg.selectAll('path.land').data([data]);
land.enter().append('path').classed('land', true);
land.attr('d', pathGenerator);
land.exit().remove();
});
var locationOptions = {
enableHighAccuracy: false,
timeout: 2e3,
maximumAge: 60 * 60 * 1e3
};
svg.on('click', function() {
navigator.geolocation.getCurrentPosition(showLocation, fallback, locationOptions);
});
function showLocation(position) {
var coords = [
position.coords.longitude,
position.coords.latitude
];
var circle = svg.selectAll('circle.location').data([coords]);
circle.enter().append('circle')
.classed('location', true)
.attr('r', d3.max([width, height]))
.attr('cx', function(d) { return projection(d)[0]; })
.attr('cy', function(d) { return projection(d)[1]; });
circle.transition().duration(2e3)
.attr('r', 3);
circle.exit().remove();
var label = svg.selectAll('text.coords').data([coords]);
label.enter().append('text')
.classed('coords', true)
.attr('x', function(d) { return 10 + projection(d)[0]; })
.attr('y', function(d) { return 5 + projection(d)[1]; });
label.transition().delay(2e3)
.text(function(d) {
var lon = d[0].toFixed(4),
lat = d[1].toFixed(4);
return lat + ', ' + lon;
});
label.exit().remove();
}
function fallback() {
console.log('Unable to get the location');
}
</script>
</body>
</html>