1

我想要一张带有 2 个标记的地图。如果我使用 LatLng(请参阅 JS 代码 / WORKS JUST FINE /),那没问题......但是一旦我尝试使用地理编码(请参阅 JS 代码 / YU NOT WORKING? /)它就不起作用。我想这都是错误的:

var adresse3=geocoder.geocode({'address': 'Winkelriedstrasse 47, 6004 Luzern'})[0].geometry.location;

谁能帮我。提前谢谢你。

var myCenter=new google.maps.LatLng(47.050944,8.309441);
var geocoder;
var map;
function initialize(){  
    var mapProp = {
      center            :myCenter         
    };
    var geocoder = new google.maps.Geocoder();
    var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
    /*WORKS JUST FINE*/
    var marker1=new google.maps.Marker({
        position: new google.maps.LatLng(47.050944,8.309441)
    });
    marker1.setMap(map);
    var infowindow1 = new google.maps.InfoWindow({
        content:"marker1"
    });
    google.maps.event.addListener(marker1, 'click', function() {
        infowindow1.open(map,marker1);
    });  
    /*Y U NOT WORKING?*/
    var adresse3=geocoder.geocode({'address': 'Winkelriedstrasse 47, 6004 Luzern'})[0].geometry.location;
    var marker3=new google.maps.Marker({
        position: adresse3
    });
    marker3.setMap(map);
    var infowindow3 = new google.maps.InfoWindow({
        content:"marker3"
    });
    google.maps.event.addListener(marker3, 'click', function() {
        infowindow3.open(map,marker3);
    }); 
}
google.maps.event.addDomListener(window, 'load', initialize);
4

3 回答 3

1

你的问题是 geocoder.geocode 是异步的,所以你必须传递一个回调函数

改编自谷歌地图文档

geocoder.geocode({'address': 'Winkelriedstrasse 47, 6004 Luzern'}, function(results, status)     {
  if (status == google.maps.GeocoderStatus.OK) {
    map.setCenter(results[0].geometry.location);
    var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
    });
  } else {
    alert("Geocode was not successful for the following reason: " + status);
  }
});
于 2013-04-12T14:56:00.900 回答
0

这就是我解决它的方法(我使用了 goMap 插件http://www.pittss.lv/jquery/gomap/

<script type="text/javascript" src="js/jquery.gomap-1.3.2.min.js"></script> 
<script type="text/javascript">
$(document).ready(function() {
    $(function(){ 
        $("#googleMap").goMap({ 
            address: 'Luzern, Schweiz', 
            zoom: 13,
            maptype: 'ROADMAP',
            mapTypeControl: false,  
            hideByClick: false
        }); 
        $.goMap.createMarker({  
            address: 'Winkelriedstrasse 47, 6004 Luzern',
            html: 'Winkelriedstrasse 47, 6004 Luzern' 
        });
    });
});
</script>

现在它工作得很好......

于 2013-04-29T11:16:53.020 回答
0

尼古拉斯,你有一个错误:

geocoder.geocode('address': 'Winkelriedstrasse 47, 6004 Luzern', function(results, status) 

使用此代码:

geocoder.geocode({'address': 'Winkelriedstrasse 47, 6004 Luzern'}, function(results, status) 
于 2013-11-01T08:22:20.593 回答