gpt4 book ai didi

javascript - 谷歌地图 V3 用户添加标记

转载 作者:数据小太阳 更新时间:2023-10-29 05:06:39 24 4
gpt4 key购买 nike

我需要一些允许用户将他们自己的标记添加到我的 map 的代码。有人有例子吗?

谢谢!

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

var stockholm = new google.maps.LatLng(59.32522, 18.07002);
var parliament = new google.maps.LatLng(59.327383, 18.06747);
var marker;
var map;


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



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

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

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


map.setCenter(location);


$.ajax({
url: 'myPHP',
data: location,
succes: function(){
alert('marker was added');
},
error: function(){
alert('marker wasn't added');
marker.setMap(null);
}
});
}

</script>

最佳答案

这不是一项艰巨的工作:

  • 在 map 上设置点击事件

    google.maps.event.addListener(map, 'click', function(event) {  placeMarker(event.latLng);});
  • 放置标记并对服务器进行 AJAX 调用以将位置保存在数据库中:

    function placeMarker(location) {  var marker = new google.maps.Marker({      position: location,       map: map  });  map.setCenter(location);  $.ajax({     url: 'myPHP',     data: location,     succes: function(){       alert('marker was added');     },     error: function(){       alert('marker wasn't added');       marker.setMap(null);     }  });}

关于javascript - 谷歌地图 V3 用户添加标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4529929/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com