【问题标题】:Javascript: how to show a google map with marker after Ajax callJavascript:如何在 Ajax 调用后显示带有标记的谷歌地图
【发布时间】:2016-06-25 12:04:25
【问题描述】:

在我的 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 内没有显示任何内容,&lt;p&gt;element 中的标题也没有显示。我已经检查console.log() data 包含来自 MySQL 的所有关于该地点的信息,它们是正确的。也许,google.maps.Marker()google.maps.Map() 是异步的吗?正确的方法是什么?谢谢

【问题讨论】:

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

标签: javascript jquery google-maps google-maps-api-3 google-maps-markers


【解决方案1】:

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

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();
}

proof of concept fiddle

代码 sn-p:

$(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" />

【讨论】:

  • 感谢您的回复。我刚刚添加了您的代码,但仍然没有出现...可能是 div 太小了?
  • 答案中的示例对我有用(我删除了 ajax 调用,因为我无法模拟它,但如果返回的数据如您所说正确,则代码应该可以工作)
  • 地理编码器返回状态“OK”吗?刚刚在发布的代码中添加了错误检查。当地理编码器未返回结果时,您的代码被编写为静默失败。
猜你喜欢
  • 2018-05-25
  • 1970-01-01
  • 2013-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-28
相关资源
最近更新 更多