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

时间:2010-12-27 07:16:06

标签: javascript google-maps

现在我有谷歌地图代码,将在地图上设置一个标记。我想要的是将单个标记移动到用户点击的任何坐标。我只想在地图上使用1个标记,因此我需要将单个标记移动到点击的任何位置。任何帮助表示赞赏。谢谢!

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

7 个答案:

答案 0 :(得分:36)

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

答案 1 :(得分:9)

当前的答案比删除和重新添加标记所做的工作要多得多。执行此操作的最佳方法是使用Google Maps API为此目的提供的setPosition()函数。

以下是您修改的代码,使用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>

答案 2 :(得分:3)

制作全局javascript变量“marker”。

然后在你的听众中添加 if marker exists 语句和remove如果为true

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

答案 3 :(得分:3)

您可以尝试:

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

答案 4 :(得分:2)

试试这个

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

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

答案 5 :(得分:1)

Burak Erdem的答案工作得很好,但实际上你不需要和数组来做到这一点,因为它只是最后一个标记就足够了,因为当你设置一个新标记时,你会删除最后一个标记。我用这几行做了它,它工作得很好:

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

答案 6 :(得分:1)

我用以下内容完成了这个:

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

它会创建一个标记,然后将其移动到每个鼠标点击位置... 我还添加了一个拖放标记动画。

不是创建多个标记,而是创建一个标记并将其移动到单击的位置。