开发者

Google Maps V3 - Save To A Database

I want to store the distance from a route in an access database, I'm almost there but only the last distance is commited to the database. Can you help me? There's only one address as origin, and I'm trying with four addresses as destination. Thanks anyway, Bill.

<html> 
<head> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
<title>Google Maps JavaScript API</title> 
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">    </script> 开发者_StackOverflow社区  
</head>

<body>

<script type="text/javascript">

var directionsService = new google.maps.DirectionsService();
var origem;
var destino;
var strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = Z:\\Projetos\\GoogleMaps\\GoogleMaps.mdb;"

//Database Connection
var cn = new ActiveXObject("ADODB.Connection");
cn.Open(strConn);

//Recordset
var rsOrigem = new ActiveXObject("ADODB.Recordset");
var sqlOrigem = "select * from tblOrigem";
rsOrigem.Open(sqlOrigem, cn);

var rsDestino = new ActiveXObject("ADODB.Recordset");
var sqlDestino = "select * from tblDestino";
rsDestino.Open(sqlDestino, cn);

rsOrigem.Movefirst();
rsDestino.Movefirst();

while(!rsDestino.eof) {
origem = rsOrigem.fields("Endereco").value;
destino = rsDestino.fields("Endereco").value;

var myOptions = {
 zoom:7,
 mapTypeId: google.maps.MapTypeId.ROADMAP
}

var request = {
   origin: origem, 
   destination: destino,
   travelMode: google.maps.DirectionsTravelMode.DRIVING
};

directionsService.route(request, function(response, status) {
  if (status == google.maps.DirectionsStatus.OK) {

     var rsGravar = new ActiveXObject("ADODB.Recordset");
     rsGravar.Open("Select * From tblDestino Where Endereco = '" + destino + "'", cn, 1, 3);

     rsGravar.Edit;
     rsGravar.fields("Distancia").value = response.routes[0].legs[0].distance.value;
     rsGravar.Update;
  }
});

rsDestino.MoveNext();
}

rsOrigem.Close();
rsDestino.Close();
rsGravar.Close();
cn.Close();

</script> 
</body> 
</html>


I doubt that you encountered a common problem in JavaScript when using loops and closures. From your description, actually only the last value in the loop is used. directionsService.route uses a callback and most likely the variable destino always refers to the last value in the loop.

Try using a closure to encapsulate the code to invoke directionsService.route, like below:

while(!rsDestino.eof) {
    origem = rsOrigem.fields("Endereco").value;
    destino = rsDestino.fields("Endereco").value;

    (function(origin, dest){
        //use variable 'origin' and 'dest' in the code
        var myOptions= ...
        var request = ...
        directionsService.route ....
    })(origem, destino);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜