I’m trying to implement some Google Maps stuff in .NET for a uni project.
However, I’m struggling with getting my coordinates to my .NET Google Maps control.
I figured the easiest way to do this would be to use the HTML5 geolocation API to get the coordinates of the current position, then grab these in my .NET code and use them to center the map.
I have the following JS code:
$(document).ready(function () {
if (Modernizr.geolocation) {
navigator.geolocation.getCurrentPosition(getCoords);
}
else {
// no support
}
function getCoords(position) {
$("#lat").val(position.coords.latitude);
$("#long").val(position.coords.longitude);
}
});
This puts the coordinates for lat and longitude in their respective hidden textboxes, #lat and #long.
Now, I want to grab them in my code-behind .NET code. I’m trying to do it like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// some other code
}
// maps
addStoreMap.enableDragging = false;
addStoreMap.enableGoogleBar = false;
// grab the coordinates here.
decimal lat = Convert.ToDecimal(hdnLat.Value);
decimal lng = Convert.ToDecimal(hdnLong.Value);
}
However, this always returns an empty value. I can’t seem to load the coordinate values into my .NET code. I get the values when I alert them through JS though. Is this because the Page_Load event happens before my JS gets executed? If so, how would I work around this?
Thanks
The
readyevent ondocumenthas no.preventDefault(), so that line is throwing an error. It was never making it to thegeolocationcode. Remove the line:Demo: http://jsfiddle.net/ThinkingStiff/mGj2W/
HTML:
Script:
Output: