Created
September 24, 2017 18:28
-
-
Save ramiroaznar/17ec5695fd9eb5f3bf0fb7e8037949c3 to your computer and use it in GitHub Desktop.
Get User Geolocation with CARTO.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, © <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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment