简体   繁体   English

Google Maps v3在地图上点击设置单个标记点

[英]Google Maps v3 set single marker point on map click

Right now I have google map code that will set a single marker on a map. 现在我有谷歌地图代码,将在地图上设置一个标记。 What I want is for that single marker to be moved to whatever coordinates the user clicks on. 我想要的是将单个标记移动到用户点击的任何坐标。 I only want 1 marker on the map, so I need that single marker to be moved to whatever location is clicked. 我只想在地图上使用1个标记,因此我需要将单个标记移动到点击的任何位置。 Any help is appreciated. 任何帮助表示赞赏。 Thanks! 谢谢!

    var initialLocation;
    var siberia = new google.maps.LatLng(60, 105);
    var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
    var browserSupportFlag =  new Boolean();



    function initialize() {
        var myOptions = {
            zoom: 6,
            mapTypeId: google.maps.MapTypeId.HYBRID
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        myListener = google.maps.event.addListener(map, 'click', function(event) {
            placeMarker(event.latLng);
            google.maps.event.removeListener(myListener);
        });
        google.maps.event.addListener(map, 'drag', function(event) {
            placeMarker(event.latLng);
            google.maps.event.removeListener(myListener);
        });

        // Try W3C Geolocation (Preferred)
        if(navigator.geolocation) {
            browserSupportFlag = true;
            navigator.geolocation.getCurrentPosition(function(position) {
                initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
                map.setCenter(initialLocation);
            }, function() {
                handleNoGeolocation(browserSupportFlag);
            });
            // Try Google Gears Geolocation
        } else if (google.gears) {
            browserSupportFlag = true;
            var geo = google.gears.factory.create('beta.geolocation');
            geo.getCurrentPosition(function(position) {
                initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
                map.setCenter(initialLocation);
            }, function() {
                handleNoGeoLocation(browserSupportFlag);
            });
            // Browser doesn't support Geolocation
        } else {
            browserSupportFlag = false;
            handleNoGeolocation(browserSupportFlag);
        }

        function handleNoGeolocation(errorFlag) {
            if (errorFlag === true) {
                alert("Geolocation service failed.");
                initialLocation = newyork;
            } else {
                alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
                initialLocation = siberia;
            }
        }

        function placeMarker(location) {
            var marker = new google.maps.Marker({
                position: location,
                map: map,
                draggable: true
            });
            map.setCenter(location);
            var markerPosition = marker.getPosition();
            populateInputs(markerPosition);
            google.maps.event.addListener(marker, "drag", function (mEvent) {
                populateInputs(mEvent.latLng);
            });
        }
        function populateInputs(pos) {
            document.getElementById("t1").value=pos.lat()
            document.getElementById("t2").value=pos.lng();
        }
    }
<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        #map_canvas {height:600px;width:800px}
    </style>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

    <script type="text/javascript">
        var map;
        var markersArray = [];

        function initMap()
        {
            var latlng = new google.maps.LatLng(41, 29);
            var myOptions = {
                zoom: 10,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

            // add a click event handler to the map object
            google.maps.event.addListener(map, "click", function(event)
            {
                // place a marker
                placeMarker(event.latLng);

                // display the lat/lng in your form's lat/lng fields
                document.getElementById("latFld").value = event.latLng.lat();
                document.getElementById("lngFld").value = event.latLng.lng();
            });
        }
        function placeMarker(location) {
            // first remove all markers if there are any
            deleteOverlays();

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

            // add marker in markers array
            markersArray.push(marker);

            //map.setCenter(location);
        }

        // Deletes all markers in the array by removing references to them
        function deleteOverlays() {
            if (markersArray) {
                for (i in markersArray) {
                    markersArray[i].setMap(null);
                }
            markersArray.length = 0;
            }
        }
    </script>
</head>

<body onload="initMap()">
    <div id="map_canvas"></div>
    <input type="text" id="latFld">
    <input type="text" id="lngFld">
</body>
</html>

The current answers do a lot more work than is necessary by removing and re-adding the marker(s). 当前的答案比删除和重新添加标记所做的工作要多得多。 The best way to do this is to use the setPosition() function that the Google Maps API provides for this purpose. 执行此操作的最佳方法是使用Google Maps API为此目的提供的setPosition()函数。

Here is your code modified to use setPosition() to move the pointer: 以下是您修改的代码,使用setPosition()移动指针:

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        #map_canvas { height:600px; width:800px }
    </style>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

    <script type="text/javascript">
    var initialLocation;
    var siberia = new google.maps.LatLng(60, 105);
    var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
    var browserSupportFlag =  new Boolean();

    function initialize() {
        var myOptions = {
            zoom: 6,
            mapTypeId: google.maps.MapTypeId.HYBRID
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        var marker;

        myListener = google.maps.event.addListener(map, 'click', function(event) {
            placeMarker(event.latLng);
        });
        google.maps.event.addListener(map, 'drag', function(event) {
            placeMarker(event.latLng);
        });

        // Try W3C Geolocation (Preferred)
        if(navigator.geolocation) {
            browserSupportFlag = true;
            navigator.geolocation.getCurrentPosition(function(position) {
                initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
                map.setCenter(initialLocation);
            }, function() {
                handleNoGeolocation(browserSupportFlag);
            });
            // Try Google Gears Geolocation
        } else if (google.gears) {
            browserSupportFlag = true;
            var geo = google.gears.factory.create('beta.geolocation');
            geo.getCurrentPosition(function(position) {
                initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
                map.setCenter(initialLocation);
            }, function() {
                handleNoGeoLocation(browserSupportFlag);
            });
            // Browser doesn't support Geolocation
        } else {
            browserSupportFlag = false;
            handleNoGeolocation(browserSupportFlag);
        }

        function handleNoGeolocation(errorFlag) {
            if (errorFlag === true) {
                alert("Geolocation service failed.");
                initialLocation = newyork;
            } else {
                alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
                initialLocation = siberia;
            }
        }

        function placeMarker(location) {
            if (marker) {
                marker.setPosition(location);
            } else {
               marker = new google.maps.Marker({
                    position: location,
                    map: map,
                    draggable: true
                });
                google.maps.event.addListener(marker, "drag", function (mEvent) {
                    populateInputs(mEvent.latLng);
                });
            }
            populateInputs(location);
        }

        function populateInputs(pos) {
            document.getElementById("t1").value=pos.lat()
            document.getElementById("t2").value=pos.lng();
        }
    }

    </script>
</head>

<body onload="initialize()">
    <div id="map_canvas"></div>
    <input type="text" id="t1">
    <input type="text" id="t2">
</body>
</html>

You can try: 你可以试试:

google.maps.event.addListener(map, 'click', function(event){
        var marker_position = event.latLng;   
marker = new google.maps.Marker({
                map: map,
                draggable: false
            }); 
       marker.setPosition(marker_position);
})

Make a global javascript variable "marker". 创建一个全局javascript变量“marker”。

Then in your listener add the if marker exists statement and remove it if true 然后在您的侦听器中添加if标记存在语句,如果为true则将其删除

myListener = google.maps.event.addListener(map, 'click', function(event) {
            if(marker){marker.setMap(null)}
            placeMarker(event.latLng);
            google.maps.event.removeListener(myListener);
        });

try this 试试这个

if (marker) { marker.setMap(null) }

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

Burak Erdem answer works fine, but actually you dont need and array to do that, it is enough one var since it is only one last marker, becouse when you set a new one, you delete inmediatly the last one. Burak Erdem的答案工作正常,但实际上你不需要和数组来做到这一点,因为它只是最后一个标记就足够了,因为当你设置一个新标记时,你删除了最后一个标记。 I did it with this few lines and it worked fine: 我用这几行做了它并且工作正常:

        var map;
        var lastMarker;
        function initialize() {
            var map_canvas = document.getElementById('map_canvas');
            var map_options = {
                center: new google.maps.LatLng(-25.363882, 131.044922),
                zoom: 8,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            map = new google.maps.Map(map_canvas, map_options)
            google.maps.event.addListener(map, 'click', function(event) {
                placeMarker(event.latLng);
            });
        }

        function placeMarker(location) {
            if (lastMarker != null)
                lastMarker.setMap(null);
            var marker = new google.maps.Marker({
                position: location,
                map: map
            });
            lastMarker = marker;
        }

        google.maps.event.addDomListener(window, 'load', initialize);

I accomplished this with the following: 我用以下方法完成了这项工作:

// create a new marker
var marker = new google.maps.Marker({
 });
//add listener to set the marker to the position on the map
google.maps.event.addListener(map, 'click', function(event) {
marker.setPosition(event.latLng);
marker.setMap(map);
marker.setAnimation(google.maps.Animation.DROP);
});

It creates a marker and then move it to each mouse click location... I also added a drop marker animation as well. 它创建一个标记,然后将其移动到每个鼠标单击位置...我还添加了一个拖放标记动画。

Instead of creating multiple markers this creates one marker and moves it to the clicked location. 这不是创建多个标记,而是创建一个标记并将其移动到单击的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM