Hai bisogno di aiuto Geocodifica inversa per aggiungere un messaggio alle coordinate GLatLng

StackOverflow https://stackoverflow.com/questions/816479

  •  03-07-2019
  •  | 
  •  

Domanda

Il mio codice : http://jsbin.com/epuxu

Con l'aiuto di SO, sono riuscito a ottenere gli indirizzi geocodificati e i relativi pin posizionati sulla mappa. Il problema è che non riesco a selezionare le coordinate per aggiungere un div #message ad esso sulla mappa perché non ho più le coordinate.

Sospetto di aver fatto qualcosa di sbagliato in questa sezione:

/* Message
--------------------*/
$("#message").appendTo(map.getPane(G_MAP_FLOAT_SHADOW_PANE));

    function displayPoint(marker, index){
        $("#message").hide();

        var moveEnd = GEvent.addListener(map, "moveend", function(){
            var markerOffset = map.fromLatLngToDivPixel(marker.getLatLng());
            $("#message")
                .fadeIn()
                .css({ top:markerOffset.y, left:markerOffset.x });

            GEvent.removeListener(moveEnd);
        });
        map.panTo(marker.getLatLng());
    }

funziona quando uso il codice di coordinate originale (questo è commentato su jsbin):

var markers = [
    [39.729308,-121.854087],
    [39.0,-121.0]
    ];

    for (var i = 0; i < markers.length; i++) {
        var point = new GLatLng(markers[i][0], markers[i][1]);
        marker = new GMarker(point);
        map.addOverlay(marker);
        markers[i] = marker;
    }

ma ho bisogno di aiuto per farlo funzionare con questo codice attuale:

function showAddress(markers) {
    if (geocoder) {
        geocoder.getLatLng(markers,
            function(point) {
                if (!point) {
                    alert(markers + " not found");
                } else {
                    marker = new GMarker(point);
                    map.addOverlay(marker);
                    markers[i] = marker;
                }
            }
        );
    }
}

for (var i = 0; i < markers.length; i++) {
    showAddress(markers[i]);
}

Sono un po 'nuovo nell'utilizzare l'API di Google Maps, quindi qualsiasi intuizione su ciò che sto facendo di sbagliato sarebbe molto utile. Grazie =]

È stato utile?

Soluzione

Temo che ci siano alcune cose sbagliate nel tuo codice: P

Ho dovuto fare un po 'di chirurgia plastica ma ecco il risultato: http://jsbin.com/atofe

La seguente è una descrizione delle modifiche che ho apportato. Fammi sapere se hai bisogno di aiuto per capire qualcosa.


<script type="text/javascript">
  document.write(marker);
</script>

Ho dovuto commentare questo perché stava causando un errore. Immagino che tu l'abbia lasciato lì per errore.

<script type="text/javascript">
  // document.write(marker);
</script>

var markers = [
  ["624 Nord Ave #20, Chico CA"],
  ["200 Nord Ave, Chico CA"],
  ["100 Nord Ave, Chico CA"],
  ["5th and Ivy, Chico CA"]
];

Dato che stiamo usando indirizzi invece di coordinate, non è necessario (in effetti non dovresti perché complica solo le cose) incapsulare ogni stringa in un array. L'ho anche rinominato in indirizzi per renderlo più chiaro e prevenire conflitti con i marker effettivi (ne parleremo più avanti).

var addresses = [
  "624 Nord Ave #20, Chico CA",
  "200 Nord Ave, Chico CA",
  "100 Nord Ave, Chico CA",
  "5th and Ivy, Chico CA"
];

function showAddress(markers) {
  if (geocoder) {
    geocoder.getLatLng(markers,
      function(point) {
        if (!point) {
          alert(markers + " not found");
        } else {
          marker = new GMarker(point);
          map.addOverlay(marker);
          markers[i] = marker;
        }
      }
    );
  }
}

for (var i = 0; i < markers.length; i++) {
  showAddress(markers[i]);
}


/* Add Markers to List
--------------------*/
$(markers).each(function(i,marker){
  $("<li>")
    .html(i+" - "+marker)
    .click(function(){
      displayPoint(marker, i);
    })
    .appendTo("#list");
  GEvent.addListener(marker, "click", function(){
    displayPoint(marker, i);
  });
});

Qui ho dovuto apportare il maggior numero di modifiche. Hai fatto un paio di errori significativi qui.

Innanzitutto, hai riutilizzato la variabile marker quando avresti dovuto usare un nuovo nome. Nel processo hai scritto sull'array di stringhe di indirizzi e hai capito male dove erano archiviate le cose (ecco perché ho rinominato l'array di stringhe di indirizzi in indirizzi ).

In secondo luogo, hai provato ad aggiungere i marker all'elenco prima il geocoder ha effettivamente restituito la sua risposta. Penso che non ti sia reso conto che getLatLng è una funzione asincrona, quindi esegue la funzione di richiamata solo dopo che il geocoder ha restituito la sua risposta. Dal momento che non hai aspettato la risposta, è stato reso " Aggiungi marcatori all'elenco " sezione inutile in quanto i marker non sono stati ancora recuperati.

Quindi, per risolvere questi problemi ho spostato " Aggiungi marcatori all'elenco " sezione all'interno della nuova funzione handleGeocoderResponse . Ciò garantisce che i marker vengano aggiunti all'elenco solo dopo che è stata restituita la risposta del geocoder. Ho anche dovuto usare una doppia chiusura poiché siamo usando un ciclo insieme a una funzione asincrona.

function handleGeocoderResponse(addr, j) {
  /*
    These are closures. We have to return a function
    that contains our Geocoder repsonse handling code
    in order to capture the values of "addr" and "j"
    as they were when they were passed in.  
  */
  return (function(point) {

    if (!point) {
      alert(addr + " not found");
    }
    else {
      var marker = new GMarker(point);
      map.addOverlay(marker);

      /* Add markers to list
      ------------------------*/
      $("<li>")
        .html(j + " - " + addr)
        .click(function(){
          displayPoint(marker, j);
        })
        .appendTo("#list");

      GEvent.addListener(marker, "click", function(){
        displayPoint(marker, j);
      });
    }

  });
}

for (var i = 0; i < addresses.length; i++) {
  if (geocoder) {
    var address = addresses[i];
    geocoder.getLatLng(
      address,
      handleGeocoderResponse(address, i)
    );
  }
}

Altri suggerimenti

Non sono sicuro di cosa stai esattamente cercando. Per " #message div " ;, intendi un finestra informativa come questo ? In tal caso, potresti fare qualcosa tra le righe seguenti (nota la riga GEvent.addListener () ):

/* Geocoded Addresses
--------------------*/
var markers = [
 ["624 Nord Ave #20, Chico CA"],
 ["200 Nord Ave, Chico CA"],
 ["100 Nord Ave, Chico CA"],
 ["5th and Ivy, Chico CA"]
];

function showAddress(markers) {
 if (geocoder) {
  geocoder.getLatLng(markers,
   function(point) {
    if (!point) {
     alert(markers + " not found");
    } else {
     marker = new GMarker(point);
     GEvent.addListener(marker, 'click', function() {
      marker.openInfoWindowHtml('<strong>Awesome place</strong><br>746 Blah street<br>1337 Awesomeville');
     });
     map.addOverlay(marker);
     markers[i] = marker;
    }
   }
  );
 }
}

for (var i = 0; i < markers.length; i++) {
 showAddress(markers[i]);
}

Provalo , fai clic su un indicatore! :)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top