Google Maps API:地理编码器和信息窗口

时间:2014-02-14 03:11:25

标签: api google-maps

我是javascript的新手,我必须说我一点也不擅长。对于我的网站,我有一个活动页面,我在其中放置了活动的位置,我希望旁边有一个地图,上面有标记位置的标记。

    <script type="text/javascript">     
var geocoder;
var map;
var marker;
function initialize() {
        var paris = new google.maps.LatLng(48.858859, 2.3470599)
        var lieu1 = new google.maps.LatLng(48.8531128, 2.3493023)
        geocoder = new google.maps.Geocoder();
        var mapOptions = {
            center: paris,
            zoom: 12
        }
        map = new google.maps.Map(
            document.getElementById('map-canvas'), mapOptions
        );
        /* 
        This works:
        var contentString = 'Lorem Ipsum';
        var infowindow = new google.maps.InfoWindow({
          content: contentString,
          maxWidth: 200
        });
        var marker = new google.maps.Marker({
            position: lieu1,
            map: map,
            title: 'Lorem Ipsum!',
            animation: google.maps.Animation.DROP
        });
        google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map,marker);
        });*/

        var contentString2 = 'Lorem Ipsum123';
        var infowindow2 = new google.maps.InfoWindow({
          content: contentString2,
          maxWidth: 200
        });
        var address = "Paris";
        geocoder.geocode( { 'address': address}, function(results) {
        var marker2 = new google.maps.Marker({
            position: results[0].geometry.location,
            map: map,
            title: 'Lorem Ipsum!',
            animation: google.maps.Animation.DROP
            });
        });
        google.maps.event.addListener(marker2, 'click', function() {
            infowindow2.open(map,marker2);
        });
    }

    function toggleBounce() {
        if (marker.getAnimation() != null) {
            marker.setAnimation(null);
        } else {
            marker.setAnimation(google.maps.Animation.BOUNCE);
        }
    }


    google.maps.event.addDomListener(window, 'load', initialize);    
</script>

这是我的代码,我添加了一些功能,如删除ping。谢谢:))

1 个答案:

答案 0 :(得分:2)

毫无疑问......

您的代码存在一个问题,报告错误:

Uncaught ReferenceError: marker2 is not defined 

因为变量marker2geocoder.geocode()方法之外不可见。您必须在标记定义之后移动事件侦听器:

    geocoder.geocode( { 'address': address}, function(results) {
    var marker2 = new google.maps.Marker({
        position: results[0].geometry.location,
        map: map,
        title: 'Lorem Ipsum!',
        animation: google.maps.Animation.DROP
        });

        google.maps.event.addListener(marker2, 'click', function() {
            infowindow2.open(map, marker2);
        });
    });

和infowindow将显示标记点击。