javascript - 固定标记在中心并拖动 map 以获得纬度,经度

标签 javascript jquery google-maps jquery-ui google-maps-api-3

我是一个示例 map ,通过单击按钮显示当前位置显示经纬度, map 上的标记可拖动以更新经纬度,但我需要在 map 上进行一些更改

我希望标记固定在 map 的中心, map 可以拖动以获得新的纬度,长如 JSFIDDLE link .

我的代码是:

var map = null;
var marker;

function showlocation() {
  // One-shot position request.
  navigator.geolocation.getCurrentPosition(callback);
}
 
function callback(position) {

  if (marker != null) {
    marker.setMap(null);
  }

  var geocoder = new google.maps.Geocoder();
  var lat = position.coords.latitude;
  var lon = position.coords.longitude;
  document.getElementById('default_latitude').value = lat;
  document.getElementById('default_longitude').value = lon;
  var latLong = new google.maps.LatLng(lat, lon);
  marker = new google.maps.Marker({
    position: latLong,
    draggable: true
  });
  marker.setMap(map);
  map.setZoom(16);
  map.setCenter(marker.getPosition());

  google.maps.event.addListener(marker, 'dragend', function() {
    geocoder.geocode({
      'latLng': marker.getPosition()
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[0]) {
          $('#default_latitude').val(marker.getPosition().lat());
          $('#default_longitude').val(marker.getPosition().lng());
        }
      }
    });
  });

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



function initMap() {
  var mapOptions = {
    center: new google.maps.LatLng(0, 0),
    zoom: 1,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map-canvas"),
    mapOptions);
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<input type="button" class="btn  pull-right map-btn" value="btn " onclick="javascript:showlocation()" />

<div id="map-canvas" style="height: 300px"></div>

<input type="text" id="default_latitude" placeholder="Latitude" />
<input type="text" id="default_longitude" placeholder="Longitude" />

最佳答案

如果你想要来自 jsfiddle you reference 的居中标记,您需要从那里包含此代码(及其关联的 CSS):

代码:

$('<div/>').addClass('centerMarker').appendTo(map.getDiv())
//do something onclick
.click(function() {
    var that = $(this);
    if (!that.data('win')) {
      that.data('win', new google.maps.InfoWindow({
        content: 'this is the center'
      }));
      that.data('win').bindTo('position', map, 'center');
    }
    that.data('win').open(map);
});

CSS:

body,
html,
#map_canvas {
  height: 100%;
  margin: 0;
}

#map_canvas .centerMarker {
  position: absolute;
  /*url of the marker*/
  background: url(http://maps.gstatic.com/mapfiles/markers2/marker.png) no-repeat;
  /*center the marker*/
  top: 50%;
  left: 50%;
  z-index: 1;
  /*fix offset when needed*/
  margin-left: -10px;
  margin-top: -34px;
  /*size of the image*/
  height: 34px;
  width: 20px;
  cursor: pointer;
}

如果您希望用该标记( map 中心)的坐标填充纬度和经度,则需要添加以下代码:

google.maps.event.addListener(map,'center_changed', function() {
  document.getElementById('default_latitude').value = map.getCenter().lat();
  document.getElementById('default_longitude').value = map.getCenter().lng();
});

proof of concept fiddle

image of resulting map

完整代码片段:

var map = null;
var marker;

function showlocation() {
  if ("geolocation" in navigator) {
    /* geolocation is available */
    // One-shot position request.
    navigator.geolocation.getCurrentPosition(callback, error);
  } else {
    /* geolocation IS NOT available */
    console.warn("geolocation IS NOT available");
  }
}

function error(err) {
  console.warn('ERROR(' + err.code + '): ' + err.message);
};

function callback(position) {

  var lat = position.coords.latitude;
  var lon = position.coords.longitude;
  document.getElementById('default_latitude').value = lat;
  document.getElementById('default_longitude').value = lon;
  var latLong = new google.maps.LatLng(lat, lon);
  map.setZoom(16);
  map.setCenter(latLong);
}
google.maps.event.addDomListener(window, 'load', initMap);



function initMap() {
  var mapOptions = {
    center: new google.maps.LatLng(0, 0),
    zoom: 1,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map-canvas"),
    mapOptions);
  google.maps.event.addListener(map, 'center_changed', function() {
    document.getElementById('default_latitude').value = map.getCenter().lat();
    document.getElementById('default_longitude').value = map.getCenter().lng();
  });
  $('<div/>').addClass('centerMarker').appendTo(map.getDiv())
    //do something onclick
    .click(function() {
      var that = $(this);
      if (!that.data('win')) {
        that.data('win', new google.maps.InfoWindow({
          content: 'this is the center'
        }));
        that.data('win').bindTo('position', map, 'center');
      }
      that.data('win').open(map);
    });
}
body,
html,
#map-canvas {
  height: 100%;
  margin: 0;
}

#map-canvas .centerMarker {
  position: absolute;
  /*url of the marker*/
  background: url(http://maps.gstatic.com/mapfiles/markers2/marker.png) no-repeat;
  /*center the marker*/
  top: 50%;
  left: 50%;
  z-index: 1;
  /*fix offset when needed*/
  margin-left: -10px;
  margin-top: -34px;
  /*size of the image*/
  height: 34px;
  width: 20px;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input type="button" class="btn  pull-right map-btn" value="btn " onclick="javascript:showlocation()" />

<div id="map-canvas" style="height: 300px"></div>

<input type="text" id="default_latitude" placeholder="Latitude" />
<input type="text" id="default_longitude" placeholder="Longitude" />

关于javascript - 固定标记在中心并拖动 map 以获得纬度,经度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36722930/

相关文章:

javascript - 在数组映射内使用新的 Promise

javascript - 如何根据图像上各个点的坐标值在图像上画一个点

javascript - 响应式设计 - 无法正常工作

javascript - 从 Google map 中清除折线,然后重新启动它

html - 对齐 Google map iFrame

javascript - 执行 javascript 并返回响应 (JavaFX/Swing)

javascript - 强制页面刷新并跳转到#section

javascript - 在 Asp.Net mvc 4 中使用 AJAX 提交表单

javascript - 在基础中使表单 javascript 工作时遇到问题

css - 需要在输入中获取一个值 id