block by pnavarrc 97a30792badaa68e195a

Location API

Full Screen

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>

    // Set the dimensions of the map
    var width  = 960,
        height = 480;

    // Create a selection for the container div and append the svg element
    var div = d3.select('#map-container'),
        svg = div.append('svg');

    // Set the size of the SVG element
    svg.attr('width', width).attr('height', height);

    // Create and configure a geographic projection
    var projection = d3.geo.equirectangular()
      .translate([width / 2, height / 2]);

    // Create and configure a path generator
    var pathGenerator = d3.geo.path()
      .projection(projection);

    // Retrieve the geographic data asynchronously
    d3.json('land.geojson', function(err, data) {

      // Throw errors on getting or parsing the file
      if (err) { throw err; }

      // Land
      var land = svg.selectAll('path.land').data([data]);

      land.enter().append('path').classed('land', true);
      land.attr('d', pathGenerator);
      land.exit().remove();

    });

    // Location API Options
    var locationOptions = {
      enableHighAccuracy: false,  // No need for high accuracy
      timeout: 2e3,               // Wait at most 2 seconds
      maximumAge: 60 * 60 * 1e3   // one hour
    };

    // Location API
    svg.on('click', function() {
      navigator.geolocation.getCurrentPosition(showLocation, fallback, locationOptions);
    });

    // It will be invoked when the user allows the application to use the Location API
    function showLocation(position) {

      // Extract the longiture and latitude from the position object
      var coords = [
        position.coords.longitude,
        position.coords.latitude
      ];

      // Circle showing the location
      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();

      // Label with the coordinates
      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>