谷歌地图在点击地图时添加信息窗口


Google Maps add Info Window on Map Click

当我点击谷歌地图上的任何位置时,我在尝试显示信息窗口时遇到了问题。当你点击地图上的任何地方时,我想显示一个标记和一个显示纬度和经度的信息窗口?如何做到这一点?

这是我迄今为止的代码:

<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>

您需要的一切都在文档中。

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

你可以试试这个,

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