var map;
map = new GMap2(document.getElementById("map_canvas"));
  map.setCenter(new GLatLng(37.4419, -122.1419), 1);
  map.setUIToDefault();

/* kolla om man har geolocation */ 
if (!navigator.geolocation) {  
document.getElementById('map_button').innerHTML ="Din webbläsarer stödjer inte geolocation!";
}

function getPosition() {
   navigator.geolocation.getCurrentPosition(function(position) {  
   update_map(position.coords.latitude, position.coords.longitude, position.coords.accuracy);  
   });  
}

function update_map(lat, long, acc) {
map.setCenter(new GLatLng(lat, long), 13);
doDrawCircle(acc/1000)
}

function doDrawCircle(rad){

	var center = map.getCenter();
	var bounds = new GLatLngBounds();

	var circlePoints = Array();

	with (Math) {

		var d = rad/6378.8;	// radians


		var lat1 = (PI/180)* center.lat(); // radians
		var lng1 = (PI/180)* center.lng(); // radians

		for (var a = 0 ; a < 361 ; a++ ) {
			var tc = (PI/180)*a;
			var y = asin(sin(lat1)*cos(d)+cos(lat1)*sin(d)*cos(tc));
			var dlng = atan2(sin(tc)*sin(d)*cos(lat1),cos(d)-sin(lat1)*sin(y));
			var x = ((lng1-dlng+PI) % (2*PI)) - PI ; // MOD function
			var point = new GLatLng(parseFloat(y*(180/PI)),parseFloat(x*(180/PI)));
			circlePoints.push(point);
			bounds.extend(point);
		}

		if (d < 1.5678565720686044) {
			circle = new GPolygon(circlePoints, '#000000', 2, 1, '#000000', 0.25);	
		}
		else {
			circle = new GPolygon(circlePoints, '#000000', 2, 1);	
		}
		map.addOverlay(circle); 

		map.setZoom(map.getBoundsZoomLevel(bounds));
	}
}
