Javascript:如何在Ajax调用后显示带有标记的谷歌地图

Javascript: how to show a google map with marker after Ajax call

本文关键字:谷歌地图 显示 调用 Ajax Javascript      更新时间:2023-09-26

在我的HTML页面中,我有:

<div id="map" class="div5" style="float: right; display:none;">
  <p id="demo_posizione"></p>
</div>

当用户执行鼠标悬停时,这是触发的 AJAX:

$(document).ready(function() {
$(document).on("mouseenter", "li", function() {
    var selector = "#" + this.id; /* id della riga <li> su cui metto il mouse */
    /* se nella riga su cui si mette il mouse è indicato un venditore (ossia esiste la sottostringa "Km") */
    if($(selector).text().indexOf("Km") > -1) {
        var strings = $(selector).text().split("-");
        $("#demo_posizione").text("Posizione venditore "+strings[strings.length - 1]);
        $.ajax({
                url: "http://lainz.softwebsrl.it/ajax/venditore",
                dataType: "json",
                crossDomain: true,
                type : 'post',
                data:
                {
                    valore: vendors_ids[$(selector).index()]
                },
                success: function (data)
                {
                    showMarker(data);
                }
         });
       }
   });
});

这是显示标记的功能:

function showMarker(data) {
//1 - getting lat and long of vendor
var vendorLatLng = null;
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address':data['indirizzo']+" "+data['civico']+", "+data['cap']+" "+data['citta']+" "+data['provincia']+", Italia"  }, function(results, status) 
{
    if (status == google.maps.GeocoderStatus.OK) {
        vendorLatLng = {lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng()};
    } 
});
//build new google maps marker with google maps api
var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: vendorLatLng
});
var marker = new google.maps.Marker({
    position: vendorLatLng,
    map: map,
    title: data['venditore']
});
$(".div5").show();
console.log("si vede il marcher?");
}

显然,带有 ID 映射的div 中没有显示任何内容,<p>元素中的标题也没有显示。我已经与console.log()核实data包含MySQL中有关该地点的所有信息,并且它们是正确的。也许,google.maps.Marker()google.maps.Map()是异步的吗?哪种方法是正确的方法?谢谢

地理编码器是异步的,您需要在回调函数中可用时使用返回的数据。

function showMarker(data) {
  //1 - getting lat and long of vendor
  var vendorLatLng = null;
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode( { 'address':data['indirizzo']+" "+data['civico']+", "+data['cap']+" "+data['citta']+" "+data['provincia']+", Italia"  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      // not required, results[0].geometry.location is a google.maps.LatLng
      vendorLatLng = {lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng()};
      //build new google maps marker with google maps api
      var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 4,
        center: results[0].geometry.location
      });
      var marker = new google.maps.Marker({
        position: results[0].geometry.location,
        map: map,
        title: data['venditore']
      });
    } else alert("Geocode failed, status: "+status); 
  });
  $(".div5").show();
}

概念验证小提琴

代码片段:

$(document).ready(function() {
  $("#btn").click(function() {
    showMarker({
      venditore: "Marker",
      indirizzo: "New York, NY",
      civico: "",
      cap: "",
      citta: "New York",
      provinca: "NY",
    });
  });
});
function showMarker(data) {
  //1 - getting lat and long of vendor
  var vendorLatLng = null;
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({
    'address': data['indirizzo'] + " " + data['civico'] + ", " + data['cap'] + " " + data['citta'] + " " + data['provincia'] + ", Italia"
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      // not required, results[0].geometry.location is a google.maps.LatLng
      vendorLatLng = {
        lat: results[0].geometry.location.lat(),
        lng: results[0].geometry.location.lng()
      };
      //build new google maps marker with google maps api
      var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 4,
        center: results[0].geometry.location
      });
      var marker = new google.maps.Marker({
        position: results[0].geometry.location,
        map: map,
        title: data['venditore']
      });
    } else alert("Geocode failed, status: "+status);
  });
  $(".div5").show();
}
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map" class="div5" style="float: right; display:none;">
  <p id="demo_posizione"></p>
</div>
<input id="btn" type="button" value="click to show map" />