Visualizzazione dei risultati da 1 a 6 su 6
  1. #1

    Problema con Geocoder in Javascript

    Ciao a tutti, ho scritto questo semplice codice per prendere dei dati da un database MySQL con PHP, creare un file XML che verrà poi elaborato da Javascript per la creazione della mappa vera e propria.

    allego prima il codice e poi vi espongo il problema:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <?
    function parseToXML($htmlStr)
    {
    $xmlStr=str_replace("<",'<',$htmlStr);
    $xmlStr=str_replace(">",'>',$xmlStr);
    $xmlStr=str_replace("&",'&',$xmlStr);
    return $xmlStr;
    }

    global $link_connessione;
    $link_connessione = mysql_connect("localhost","root","");
    //$link_connessione = mysql_connect("xx.xxx.xxx.xx","Sqlxxxxxx","xxxxxxx x");


    if(!$link_connessione)
    die("Impossibile connettersi a MySql");
    //connessione al DB
    mysql_select_db("test", $link_connessione);

    $query_rsRecordset = "SELECT * FROM markers ORDER BY ID, lat DESC";
    $rsRecordset = mysql_query($query_rsRecordset, $link_connessione) or die(mysql_error());
    $row_rsRecordset = mysql_fetch_assoc($rsRecordset);
    $totalRows_rsRecordset = mysql_num_rows($rsRecordset);

    // START STORING DATA IN VARIABLE TO PLACE IN XML FILE
    if($totalRows_rsRecordset > 0) {
    echo $totalRows_rsRecordset;
    // STORE NAME OF TABLE
    $strXML="";
    $strXML = "<markers>";
    echo $strXML;
    // STORE FIELD AND FIELD DATA IN ONE HIARCHY, REPEAT FOR MULTIPLE FIELDS
    do {

    $strXML = $strXML. '<marker ';
    $strXML = $strXML. 'name="' . parseToXML(($row_rsRecordset['name'])) . '" ';
    $strXML = $strXML. 'address="' . ($row_rsRecordset['address']) . '" ';
    $strXML = $strXML. 'lat="' . $row_rsRecordset['lat'] . '" ';
    $strXML = $strXML. 'lng="' . $row_rsRecordset['lng'] . '" ';
    $strXML = $strXML. 'type="' . $row_rsRecordset['type'] . '" ';
    $strXML = $strXML. "/>";

    } while ($row_rsRecordset = mysql_fetch_assoc($rsRecordset));


    $strXML = $strXML . "</markers>";

    // OPEN FILE, WRITE TO FILE, CLOSE FILE, CLOSE RECORDSET
    $XMLFile = fopen("finale.xml", "w") or die("can't open file");

    fwrite($XMLFile, $strXML);
    fclose($XMLFile);
    }

    ?>

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Google Maps AJAX + mySQL/PHP Example</title>
    <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAR0TWf73rulOP_SnETQPF KxRj5djmSsmVAgDaRb1psFcJlThRhxSjxifqM96NjrBsBn2XrZ WSE-QQqQ"
    type="text/javascript"></script>
    <script type="text/javascript">
    //<![CDATA[

    var iconBlue = new GIcon();
    iconBlue.image = 'ico/2.png';
    iconBlue.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
    iconBlue.iconSize = new GSize(20, 20);
    iconBlue.shadowSize = new GSize(22, 20);
    iconBlue.iconAnchor = new GPoint(6, 20);
    iconBlue.infoWindowAnchor = new GPoint(5, 1);


    var iconRed = new GIcon();
    iconRed.image = 'ico/1.png';
    iconRed.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
    iconRed.iconSize = new GSize(20, 20);
    iconRed.shadowSize = new GSize(22, 20);
    iconRed.iconAnchor = new GPoint(6, 20);
    iconRed.infoWindowAnchor = new GPoint(5, 1);

    var customIcons = [];
    customIcons["restaurant"] = iconBlue;
    customIcons["bar"] = iconRed;

    function load() {

    if (GBrowserIsCompatible()) {
    var map = new GMap2(document.getElementById("map"));
    map.enableScrollWheelZoom();
    map.setMapType(G_SATELLITE_MAP);
    map.addControl(new GSmallMapControl());
    //map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(50, 0), 2);

    //Test per comportarmi in modo diverso se ci sono le coordinate o no
    GDownloadUrl("finale.xml", function(data) {
    var xml = GXml.parse(data);
    var markers = xml.documentElement.getElementsByTagName("marker") ;

    for (var i = 1; i < markers.length; i++) {

    var punto = markers[i].getAttribute("lat");

    if ((!punto) || (punto == 0.000000))
    {

    var address = markers[i].getAttribute("address");
    var name = markers[i].getAttribute("name");
    var type = markers[i].getAttribute("type");
    alert (address);
    geocoder = new GClientGeocoder();
    geocoder.getLatLng(address,function(point)
    {
    if (!point)
    {
    // Indirizzo non trovato!
    alert(address + " non trovato!");
    }
    else
    {

    // Crea il marker

    var marker = createMarker(point, name, address, type);
    map.addOverlay(marker);
    }
    })
    }
    else
    {
    var name = markers[i].getAttribute("name");
    var address = markers[i].getAttribute("address");
    var type = markers[i].getAttribute("type");
    var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
    parseFloat(markers[i].getAttribute("lng")));
    var marker = createMarker(point, name, address, type);
    map.addOverlay(marker);
    }
    }

    });

    }
    }
    function createMarker(point, name, address, type) {
    var marker = new GMarker(point, customIcons[type]);
    var html = "" + name + "
    " + address;
    GEvent.addListener(marker, 'click', function() {
    marker.openInfoWindowHtml(html);
    });
    return marker;
    }

    </script>
    </head>

    <body onload="load()" onunload="GUnload()">
    <div id="map" style="width: 800px; height: 300px"></div>

    </body>
    </html>


    Ora, i punti sulla mappa vengono TUTTI creati correttamente ma per questi casi (if ((!punto) || (punto == 0.000000))) i punti sono sì corretti ma tengono come informazioni descrittive quelle dell'ultimo record del database.
    Ho inserito anche degli alert nella funzione ed "i" quando passa dalla funzione geocoder.getLatLng(address,function(point) è a 13 nonostante io abbia solo 12 record, è come se eseguisse la funzione SOLO DOPO la fine del ciclo for...
    qualcuno sa come poter risolvere?
    Grazie a tutti

  2. #2
    prova a mettere un alert che stampi markers.length e vediamo che ti stampa, perchè c'è qualcosa che non mi torna.
    Poi fai partire questo ciclo da zero
    for (var i = 1; i < markers.length; i++)
    e dicci che succede

    Occhio che nel tuo codice c'è una stringa di connessione a un db che sarebbe meglio togliere da qui. Se non puoi editare chiedi a un moderatore

  3. #3
    Ho risolto mettendo la funzione di callback esterna al ciclo for perchè, anche se ancora inspiegabilmente, la funzione veniva chiamata alla fine del ciclo for e non di volta in volta restituendo sì il punto corretto ma non la descrizione html che mi serviva, se vi può servire ditemelo e vi posto il codice

  4. #4
    in generale credo, e qui lo scrivo così se sbaglio qualcuno mi possa correggere, se metti una chiamata asincrona dentro un ciclo e vuoi usare il contatore del ciclo nella callback, nel momento in cui vengono eseguite le callback il contatore è stato incrementato più e più volte, e se l'esecuzione è uscita dal ciclo tutte le callback vedranno addirittura lo stesso identico valore del contatore.

  5. #5
    esatto, l'unica cosa inspiegabile è che, in questo caso, mi sarei aspettato che anche i punti (4, 5, 10000) coincidessero ed invece i punti sulla mappa vengono calcolati correttamente mentre le descrizioni per i tooltip sono sbagliate.
    Facendo invece un richiamo esterno al ciclo, il ciclo si ferma finchè la funzione stessa non restituisce un valore, restituendo così tutti i valori corretti

  6. #6
    Mi sono comunque accorto di un "piccolissimo" problema...
    su Interent Explorer non ne vuole sapere di funzionare!!
    Non si vede neanche un marker

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2026 vBulletin Solutions, Inc. All rights reserved.