Skip to content

Instantly share code, notes, and snippets.

@ramiroaznar
Created September 24, 2017 18:28

Revisions

  1. ramiroaznar created this gist Sep 24, 2017.
    75 changes: 75 additions & 0 deletions index.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,75 @@
    <!DOCTYPE html>
    <html>
    <head>
    <title>Get User Geolocation with CARTO.js</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <link rel="shortcut icon" href="http://cartodb.com/assets/favicon.ico" />

    <link rel="stylesheet" href="https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/themes/css/cartodb.css" />
    <script src="https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/cartodb.js"></script>

    <style>
    html, body, #map {
    height: 100%;
    padding: 0;
    margin: 0;
    }
    </style>

    </head>
    <body>
    <div id="map"></div>

    <script>
    function main() {

    // Try HTML5 geolocation
    if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {

    var lat = position.coords.latitude,
    lng = position.coords.longitude,
    query = "SELECT 1 as cartodb_id, 'You are here' as message, ST_Transform(CDB_LatLng(" + lat + ", " + lng + "), 3857) as the_geom_webmercator",
    style = "#layer{marker-width: 7; marker-fill: red; marker-line-width: 0.5; marker-line-color: white; text-name: [message]; text-face-name: 'Open Sans Bold'; text-size: 12; text-fill: #FFFFFF; text-halo-fill: fadeout(#000000, 30%); text-halo-radius: 2; text-allow-overlap: true; text-placement: point; text-placement-type: simple; text-dy: 10;}";

    console.log(lat, lng, query, style);

    var map = L.map('map', {
    zoomControl: false,
    center: [lat, lng],
    zoom: 9
    });

    // add basemap
    L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, &copy; <a href="http://cartodb.com/attributions">CARTO</a>'}).addTo(map);

    // add cartodb layer
    cartodb.createLayer(map, {
    user_name: 'ramirocartodb',
    type: 'cartodb',
    sublayers: [{
    sql: query,
    cartocss: style,
    }]
    }, {https: true}).addTo(map)

    .done(function(layer){

    var sublayer = layer.getSubLayer(0);

    console.log(sublayer);

    });

    });

    } else {
    // Browser doesn't support Geolocation
    alert("Geolocation is disabled");
    }
    }
    window.onload = main;
    </script>
    </body>
    </html>