how do i convert Lat and Long to uk postcode with Javascript - javascript

I'm trying to make use of HTML5 geolocation for a project I'm working on.
It seems pretty straighforward to get the Lat and Long of where a user is, via geolocation.
Problem is, I need to convert this to a UK postcode, and am strugging as I'm trying to learn javascript.
The code I have working is:
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
alert("Geolocation is not supported by this browser");
}
function displayPosition(position) {
alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
var Lat = position.coords.latitude;
var Long = position.coords.longitude;
var inputField = document.getElementById("addressInput");
inputField.value = Lat + Long;
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
I've found this site, whihc does exactly the kind of thing I want to achieve:
http://www.latlong.net/Show-Latitude-Longitude.html
Can anyone give me some tips on how to get this working?
Any advice would be great
thanks in advance
=========================
Amended code:
//var long = '50.**************', lat = '0.**************'
var Lat='';
var Long='';
var coordsObj = {coords:{latitude:Lat, longitude:Long}};
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
alert("Geolocation is not supported by this browser");
}
function displayPosition(position) {
console.log(position, position.coords)
console.log("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
var Lat = position.coords.latitude;
alert(Lat);
var Long = position.coords.longitude;
alert(Long);
var inputField = document.getElementById("addressInput");
inputField.value = Lat + Long;
return [Lat, Long];
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
function reverseGeoLookup(lon, lat) {
var req = new XMLHttpRequest()
req.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=true", true)
req.onreadystatechange = function() {
if(req.readyState == 4) {
var result = JSON.parse(req.response).results
for(var i = 0, length = result.length; i < length; i++) {
for(var j = 0; j < result[i].address_components.length; j++) {
var component = result[i].address_components[j]
if(~component.types.indexOf("postal_code")) {
var out = document.getElementById('output')
out.innerHTML += component.long_name
}
}
}
}
}
req.send()
}
var latlng = displayPosition(coordsObj)
reverseGeoLookup.apply(this, latlng)

There's now a free UK government alternative to the other options listed here. Go to http://postcodes.io/ to see the details of the API and examples. It also supports reverse lookups which is what you're after

You could use the Google Maps reverse geocoding API. This allows you to map a lat, long pair to a set of addresses. For example:
function reverseGeoLookup(lon, lat) {
//make a ajax request -- in prod just use whatever libraryyou have to provide this
//probably jquery's $.get
var req = new XMLHttpRequest()
//put the longitude and latitude into the API query
req.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=true", true)
//this is just the result callback -- it's the function arg to $.get, essentially
req.onreadystatechange = function() {
if(req.readyState == 4) {
//again jquery will parse for you, but we want the results field
var result = JSON.parse(req.response).results
//the maps API returns a list of increasingly general results
//i.e. street, suburb, town, city, region, country
for(var i = 0, length = result.length; i < length; i++) {
//each result has an address with multiple parts (it's all in the reference)
for(var j = 0; j < result[i].address_components.length; j++) {
var component = result[i].address_components[j]
//if the address component has postal code then write it out
if(~component.types.indexOf("postal_code")) {
var out = document.getElementById('output')
out.innerHTML += component.long_name
}
}
}
}
}
//dispatch the XHR... just use jquery
req.send()
}
I put this example into a js fiddle too, here.
Hope this helps.

I've made some changes to kieran's fiddle to more to help fully answer the question of getting a UK postcode from an html5 geolocation.
var x=document.getElementById("output");
getLocation();
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.watchPosition(reverseGeoLookup);
}
else
{
x.innerHTML="Geolocation is not supported by this browser.";
}
}
function reverseGeoLookup(position) {
console.log(position);
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var req = new XMLHttpRequest()
req.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=true", true)
req.onreadystatechange = function() {
if(req.readyState == 4) {
var result = JSON.parse(req.response).results
for(var i = 0, length = result.length; i < length; i++) {
for(var j = 0; j < result[i].address_components.length; j++) {
var component = result[i].address_components[j]
//console.log(component.long_name);
if(~component.types.indexOf("postal_code")) {
var out = document.getElementById('output');
out.innerHTML = 'Approximate Post Code for your location is ' + component.long_name;
return false;
}
}
}
}
}
req.send()
}
http://jsfiddle.net/ef72Q/28/

Related

Google map marker with angularjs for large data

I am building an widget where user can upload an excel file and the places are get marked in the google map.
The following code works, but issue comes when i am reading an large excel file with 10k amount of data, the browser gets stuck. I am using a for loop and adding some timeout to get the data from the google api.
I pass the city name and get the latitude and longitude and mark it on the map.
Is there a better way i can implement?
Here is the code:
function googleMapsInit(widId, $scope, $http, $rootScope, $mdDialog) {
$scope.finish = function() {
var objIndex = getRootObjectById(widId, $rootScope.dashboard.widgets);
$mdDialog.hide();
document.getElementById('map').innerHTML = "";
//excel data
var array = JSON.parse($rootScope.json_string);
$scope.locationData = [];
//dividing it to chunks
var k,j,temparray,chunk = 8;
for (k=0,j=array.length; k<j; k+=chunk) {
temparray = array.slice(k,k+chunk);
var i;
//getting the longitude and latitude from the google geo api
for(i=0;i < temparray.length ; i++){
Geocode(temparray[i].PLACE_OF_ACCIDENT);
}
}
//sometimes data gets delayed
setTimeout(function(){ googleMap(); }, 5000);
};
function Geocode(address) {
var obj = {};
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
obj = {
lat : results[0].geometry.location.G,
lng : results[0].geometry.location.K
};
setTimeout(function(){ $scope.locationData.push(obj); }, 100);
}
else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function() {
Geocode(address);
}, 100);
}
else if (status === google.maps.GeocoderStatus.ZERO_LIMIT) {
setTimeout(function() {
Geocode(address);
}, 100);
}
else {
}
});
}
function googleMap() {
var dataStore = $scope.locationData;
var array = JSON.parse($rootScope.json_string);
var map = new google.maps.Map(document.getElementById('map'),{
center: {lat: 7.85, lng: 80.65},
zoom: 6 });
var pinImageGreen = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/icons/green-dot.png");
var pinImageBlue = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/icons/blue-dot.png");
var marker = [];
var k;
for(k=0; k < array.length; k++){
marker[k] = new google.maps.Marker({
position: {lat: $scope.locationData[k].lat, lng: $scope.locationData[k].lng},
map: map,
title: array[k].PLACE_OF_ACCIDENT,
icon: pinImageGreen,
VEHICLE_TYPE: array[k].VEHICLE_TYPE,
VEHICLE_USAGE: array[k].VEHICLE_USAGE,
VEHICLE_CLASS: array[k].VEHICLE_CLASS
});
marker[k].addListener('click', function(data) {
var j;
for(j=0;j<array.length;j++){
if(($scope.locationData[j].lat == data.latLng.G) && ($scope.locationData[j].lng == data.latLng.K )){
document.getElementById("details").innerHTML =
array[j].PLACE_OF_ACCIDENT + "</br>" +
array[j].VEHICLE_TYPE + "</br>" +
array[j].VEHICLE_USAGE + "</br>" +
array[j].VEHICLE_CLASS + "</br>" ;
}
}
});
}
}
$scope.cancel = function() {
$mdDialog.hide();
};
}
One way to slightly improve performance is this: Instead of adding markers to the map one at a time, just create the markers array separately and then add them all at once to the map. Here is a sample code:
var markersData = [];
for (var i = 0; i < myArray.length; i++) {
var item = scope.myArray[i];
if (item.lat != undefined && item.lon != undefined) {
var icon = 'icon.png';
markersData.push({
lat: item.lat,
lng: item.lon,
title: 'xyz'
});
}
}
map.addMarkers(markersData);
By the way I have used "gmaps.js" for this which simplifies coding google maps, but you don't necessarily need it. The general idea is to avoid adding markers to the map inside the loop, one by one.

google maps direction service not permitting nested plain js call to elevation service

I have a project whereby a route is generated by the google maps directions service, and I have a loop to obtain all coordinates along it (using a functioned called showPathInfo - see base of query for full HTML):
var tp = result.routes[0].legs[i].steps[j].path[k]; // local variable
var z = new google.maps.LatLng(tp.lat(),tp.lng()); // local variable
I wish to make a call to the elevation service during each loop iteration using:
elevation = getElevation(z); // global variable but NOT an array
where getElevation is a function (see base of query for full HTML).
For some reason, even though the coords are correctly passed to the function, and are rendered appropriately into a getElevationForLocations object (I have checked this by having the getElevation return variables before the getElevationForLocations call); the service returns "undefined" for
return results[0].elevation;
I am interested in getting this solution to work to take advantage of the higher accuracy afforded to individual elevation service requests, and am trying to avoid batch requests with locations[] as a full array or using the getElevationForPath function.
Admittedly there is the problem of a limit to the number of single elevation requests that can be made per second and in total, but I have tried slowing down the code execution and limiting the distances in order to get this to work at least once:
function wait() { setTimeout(function () {
elevation = getElevation(z); // here defined as a global variable
}, 500);}
wait();
Does anyone have any ideas why such a nested call like this cannot work?
The full fiddle html code is as follows:
<!DOCTYPE html>
<html><head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>html, body, #map-canvas {height: 100%;margin: 0px;padding: 0px}</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
var rendererOptions = { draggable: true };
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
var directionsService = new google.maps.DirectionsService();
var infowindow = new google.maps.InfoWindow();
var map;
var elevation; // *******************
var elevator;
var start = new google.maps.LatLng(55.60289406109326, -2.88885779678822);
var wpnt1 = new google.maps.LatLng(55.59226543103951, -2.91247397661209);
var wpnt2 = new google.maps.LatLng(55.57330299699533, -2.88813963532448);
var wpnt3 = new google.maps.LatLng(55.58132161006218, -2.84357875585556);
var wpnt4 = new google.maps.LatLng(55.58602383263128, -2.87256672978401);
var wpnt5 = new google.maps.LatLng(55.60450928199337, -2.89154000580311);
var ended = new google.maps.LatLng(55.60289406109326, -2.88885779678822);
function initialize() {
elevator = new google.maps.ElevationService();
var mapOptions = { zoom: 10,center: start };
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directionsPanel'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
document.getElementById('points').innerHTML = "";
showPathInfo(directionsDisplay.getDirections());
});
calcRoute();
} // ***** End of initialise function
function calcRoute() {
var request = {origin: start,destination: ended,
waypoints:[{location: wpnt1}, {location: wpnt2}, {location: wpnt3}, {location: wpnt4}, {location: wpnt5}],
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function showPathInfo(result) {
var total = 0;
var ns = 0;
var pt = 0;
var myroute = result.routes[0];
document.getElementById('points').insertAdjacentHTML('beforeend', '<th>Point</th><th>Lat</th><th>Lon</th><th>Elevation</th>');
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
ns += myroute.legs[i].steps.length;
for (var j = 0; j < myroute.legs[i].steps.length; j++) {
for (var k = 0; k < myroute.legs[i].steps[j].path.length; k++) {
var tp = myroute.legs[i].steps[j].path[k];
var z = new google.maps.LatLng(tp.lat(),tp.lng());
//function wait() { setTimeout(function () {
elevation = getElevation(z);
//}, 500);} // End of getAndWait
//wait();
document.getElementById('points').insertAdjacentHTML('beforeend',
'<tr><td>' + pt + '</td><td>' +
tp.lat().toFixed(7) + '</td><td>' +
tp.lng().toFixed(7) + '</td><td>' +
elevation + '</td></tr>');
pt += 1;
}
}
}
total = total / 1000.0;
document.getElementById('total').innerHTML = total + ' km';
document.getElementById('legs').innerHTML = myroute.legs.length;
document.getElementById('steps').innerHTML = ns;
}
function getElevation(z) {
var locations = [];
var clickedLocation = z;
locations.push(clickedLocation);
var positionalRequest = { 'locations': locations }
elevator.getElevationForLocations(positionalRequest, function(results, status) {
if (status == google.maps.ElevationStatus.OK) {
// Retrieve the first result
if (results[0]) {
return results[0].elevation;
} else {
return 'No results found';
}
} else {
return 'Elevation service failed due to: ' + status;
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas" style="float:left;width:70%; height:100%"></div>
<div id="directionsPanel" style="float:right;width:30%;height 25%">
<p>Total Distance: <span id="total"></span> Legs: <span id="legs"></span>Steps: <span id="steps"></span></p>
<table id="points"></table>
</div>
</body>
</html>
Postscript
In the end it was the use of a Bluebird promise loop that worked.
<script src="https://cdn.jsdelivr.net/bluebird/latest/bluebird.js"></script>
For the record I was not using node.js or any other functionality other than just plain js plus bluebird. Promises are dealt with in detail by many answers in StackOverflow so I recommend reading these and looking through the API: https://github.com/petkaantonov/bluebird/blob/master/API.md .

Will there be any inconsistency with the value calculated?

I have a javascript code like below to calculate the total distance between n markers.
var distance = 0;
function updateTimeAndDistance(timeAndPath) {
realtracPath = timeAndPath.path;
getDistance();
console.log("calculated distance : " + distance);
}
function getDistance() {
for ( var i = 0; i < realtracPath.length - 1 ; i++) {
var startPos = new google.maps.LatLng(realtracPath[i].lat, realtracPath[i].lng);
var endPos = new google.maps.LatLng(realtracPath[i+1].lat, realtracPath[i+1].lng);
var request = {
origin : startPos,
destination : endPos,
travelMode : google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
distance += response.routes[0].legs[0].distance.value;
}
});
}
}
but I am worried that, will there be any inconsistency in the value of the distance calculated as the distance is calculated asynchronously.
EDIT: every time I run this, I am getting distance as zero. I am not understanding why, though I have used the global distance variable.
Thanks.
Try introducing an async callback function like so;
var distance = 0;
function updateTimeAndDistance(timeAndPath) {
realtracPath = timeAndPath.path;
getDistance(function(){
console.log("calculated distance : " + distance);
});
}
function getDistance(cb) {
var latch = realtrackPath.length;
for ( var i = 0; i < realtracPath.length - 1 ; i++) {
var startPos = new google.maps.LatLng(realtracPath[i].lat, realtracPath[i].lng);
var endPos = new google.maps.LatLng(realtracPath[i+1].lat, realtracPath[i+1].lng);
var request = {
origin : startPos,
destination : endPos,
travelMode : google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
distance += response.routes[0].legs[0].distance.value;
latch--
if (latch==0){
cb()
}
}
});
}
}
Note: If the status does not come back as OK nothing will happen. It can be quite handy to have callbacks with function signatures that pass booleans indicating errors etc.

Convert "[52.43242, 4.43242]" to google LatLng

i have a very simple question,
I try to let google calculate the distance between an adress and a gsp-variable containing
[53.57532, 10.01534]
i´m not able to get variable ${center} to an google.maps.LatLng-Object
heres the function
jQuery(document).ready(function() {
var result = '${center}';
console.log(result);// [53.57532, 10.01534]
var origin = new google.maps.LatLng(55.930385, -3.118425);
var destination = new google.maps.LatLng(result);
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
avoidHighways: false,
avoidTolls: false
}, callback);
function callback(response, status) {
if (status == google.maps.DistanceMatrixStatus.OK) {
console.log('status OK!');//status OK!
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
var distance = element.distance.text;
var duration = element.duration.text;
var from = origins[i];
var to = destinations[j];
console.log(distance);//Uncaught TypeError: Cannot read property 'text' of undefined
}
}
}
}
});
in the "source code" above google throws error
Uncaught TypeError: Cannot read property 'text' of undefined
i tryed alot of senseless shit, but i just don get it,
maybe someone can give a hint what i am doing wrong?
thanks in advance
according to the comments here´s my gmap3 also failing, but i woulkd rather this one to put to work but i guess it´s the same problem here, that converting to lat lon does´nt work
function getDistance(adress){
var to;
var result = '${center}';
$("#getdistance").gmap3({
getdistance:{
options:{
origins:adress,
destinations:result ,
travelMode: google.maps.TravelMode.DRIVING
},
callback: function(results, status){
var html = "";
if (results){
for (var i = 0; i < results.rows.length; i++){
var elements = results.rows[i].elements;
for(var j=0; j<elements.length; j++){
switch(elements[j].status){
case "OK":
html += elements[j].distance.text + " (" + elements[j].duration.text + ")<br />";
break;
case "NOT_FOUND":
html += "The origin and/or destination of this pairing could not be geocoded<br />";
break;
case "ZERO_RESULTS":
html += "No route could be found between the origin and destination.<br />";
break;
}
}
}
} else {
html = "error";
}
console.log('start '+adress);
console.log('start '+latte);
console.log('start '+html);
}
}
});
}
here i´m parsing an adress as a string to the function as adress
How about
var result = ${center};
var destination = new google.maps.LatLng(result[0], result[1]);
google.maps.LatLng doesn't accept an array. Arguments it accepts are: number, number, bool.
https://developers.google.com/maps/documentation/javascript/reference#LatLng

Asp.Net Page JavaScript alert command alters program behaviour

I am new to JavaScript.
Writing a script that uses GooogleMaps API
Working OK. Get Lat Lngs from Database, Make markers, put on Map.
Decided to move a function call up a level, (it was in the OnSuccess method of a PageMethod call). Stopped working.
Put in alerts to diagnose. Starts working.
Narrowed down to having alert at top of called function MakeLatLngs().
MakeLatLngs code appears to execute regardless of alert being present or commented out.
It is just that the map displays with alert statement in and doesn't display with alert statement commented out.
The alert is just text and not using any variable. So I am at a loss to understand what is going on here.
The same thing is happening in the function that draws the map DrawMap(). I put an informative alert at the start of the function and the map draws. Leave it out and the map doesn't.
Any clues as to what is going on would be appreciated?
The script is below.
Flow starts at function Initialise at bottom of script.
thanks
var myPositions = [];
var myRoutes = [];
var myString = [];
var myLatLngs = [];
var myTitles = [];
var NumPoints;
var map;
var poly;
var RouteName;
var myMarkers = [];
var myMapCentre = new google.maps.LatLng(-41.2954168187213, 174.767133718655);
function DrawMap() {
alert("Generating Points for " + RouteName);// Need this to display
var thisLatLng = myLatLngs[0];
var myOptions = {
zoom: 8,
center: thisLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
MakeMarkers();
RouteLine();
}
function OnSuccess1(response) {
myPositions = new Array();
myString = response;
NumPoints = response.length;
for (var i = 0; i < NumPoints; i++) {
myPositions[i] = response[i];
}
}
function OnError1(response) {
}
function Marker()
{
this.meterId=0;
this.latLng="";
}
function OnSuccess(response) {
myPositions = new Array();
myString = response;
NumPoints = response.length;
alert("Numpoints is " + NumPoints);
for (var i = 0; i < NumPoints; i++) {
myPositions[i] = response[i];
}
alert("Exiting OnSuccess");
//MakeLatLngs(); //ORIGINAL POSITION OF LATLNG CALL
return true;
}
function setRoute() {
RouteName = prompt(' What route?', '');
}
function OnError(error) {
alert("In Error");
}
function RouteLine() {
var polyOptions = {
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
}
poly = new google.maps.Polyline(polyOptions);
poly.setMap(map);
var path = poly.getPath();
for (var i = 0; i < NumPoints; i++) {
path.push(myLatLngs[i]);
}
}
function MakeLatLngs() {
alert("You need me now " );//Got to have this to display OK when called from LoadData
myLatLngs = new Array();
for (var i = 0; i < NumPoints; i++) {
var sMarker = myPositions[i];
var SeqPos = sMarker.indexOf(";");
var latLngPos = sMarker.indexOf(";", SeqPos + 1);
var marker = sMarker.substring(0, latLngPos);
//alert("Marker is " + marker);
//var Seq = sMarker.substring(latLngPos + 1, SeqPos - latLngPos);
myTitles[i] = marker;
//alert("MeterId is " + marker);
var sLatLng = sMarker.substring(latLngPos + 1)
//alert("SLatLng is " + sLatLng);
var pos = sLatLng.indexOf(",");
//alert("pos is " + pos);
var sLat = sLatLng.substring(0, pos);
//alert("sLat is " + sLat);
var sLng = sLatLng.substring(pos + 1, sLatLng.length - 1);
//alert("sLng is " + sLng);
var lat = parseFloat(sLat);
var lng = parseFloat(sLng);
//alert("Lat is " + lat + " Long is " + lng);
if (!isNaN(lng) && !isNaN(lat) && lat != 0 && lng != 0 ) {
var latlng = new google.maps.LatLng(lat, lng);
myLatLngs[i] = latlng;
}
}
alert("Exiting MakeLatLngs")
}
function MakeMarkers() {
for (var i = 0; i < NumPoints; i++) {
var sTitle = "MyValue " + i;
var marker = new google.maps.Marker({
position: myLatLngs[i],
map: map,
title: myTitles[i]
});
}
}
function LoadData() {
setRoute();//Get the desired route from the user
PageMethods.GetMarkers(RouteName, OnSuccess, OnError);
MakeLatLngs(); //Works here ONLY WHEN AN ALERT IS FIRST LINE in FUNCTION. Orginal call was at end of OnSuccess
//PageMethods.GetRouteBoundaries(OnSuccess1, OnError1);
return false;
}
function initialize() {
LoadData();
DrawMap();
}
google.maps.event.addDomListener(window, 'load', initialize);//yes you do need this with or without <body onload="initialise">
The reason is that your PageMethods.GetMarkers is asynchronous, so the data hasn't loaded when you invoke DrawMap. I guess when you use the alert, it pauses execution long enough for the data to load. Put the DrawMap method inside the OnSuccess of the page method, and that should solve the problem.

Categories