Google地图在地图上添加信息窗口单击

时间:2014-10-30 04:05:49

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

当我点击谷歌地图上的任何地方时,我一直在尝试显示信息窗口时遇到问题。当你点击地图上的任何地方时,我想显示一个标记和一个显示纬度和经度的信息窗口?怎么办呢?

这是我到目前为止的代码:

<script type="text/javascript">

    var locations = <?php echo json_encode($js_array);?>;
    var lats = <?php echo json_encode($lats);?>;
    var lats = <?php echo json_encode($iphoto);?>;

    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 10,
        center: new google.maps.LatLng(<?php echo $latitude;?>, <?php echo $longitude;?>),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;
    var latlngbound = new google.maps.LatLngBounds();

    for (i = 0; i < locations.length; i++) {  
        console.log(locations[i].lat);
        // CREATE LATLNG OBJECT AND USE IT TO EXTEND THE LATLNGBOUNDS
        var latlng = new google.maps.LatLng(locations[i].latitude, locations[i].longitude);
        latlngbound .extend(latlng);

        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i].latitude, locations[i].longitude),
            map: map,
            animation: google.maps.Animation.DROP,
            icon: {size: new google.maps.Size(30, 30),
            scaledSize: new google.maps.Size(30, 30),
            url: locations[i].iprofilephoto,}
        });


        google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
                infowindow.setContent("<div><img style='width:40px;height:40px' src='"+locations[i].iprofilephoto+"'>"+locations[i].name+"</div><div><img style='width:100px;height:100px' src='"+locations[i].iphoto+"'></div>");
                infowindow.open(map, marker);
             }
        })(marker, i));
        map.fitBounds(latlngbound);

    }
</script>

2 个答案:

答案 0 :(得分:1)

您需要的一切都在documentation

google.maps.event.addListener(map, 'click', function(e) {

    var marker = new google.maps.Marker({
        position: e.latLng,
        map: map
    });

    infowindow.setContent(e.latLng.toString());
    infowindow.open(map, marker);
}); 

答案 1 :(得分:0)

您可以尝试这个,

    var infowindow;
    google.maps.event.addListener(map, 'click', function( event ){ 
        if(isInfoWindowOpen(infowindow)) infowindow.close();
        infowindow = new google.maps.InfoWindow({
            content:"Latitude: "+String(event.latLng.lat()).substring(0,7)+" "+"<br/>Longitude: "+String(event.latLng.lng()).substring(0,7),
            position: event.latLng
        });
        infowindow.open(map);
    });

    function isInfoWindowOpen(infoWindow){
        if(infoWindow == null) return false;
        var map = infoWindow.getMap();
        return (map !== null && typeof map !== "undefined");
    }