草庐IT

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

coder 2025-02-05 原文

我是一个示例 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

完整代码片段:

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 - 固定标记在中心并拖动 map 以获得纬度,经度的更多相关文章

  1. ruby - 无法在 60 秒内获得稳定的 Firefox 连接 (127.0.0.1 :7055) - 2

    我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类

  2. ruby - 在 Ruby 中将整数格式化为固定长度的字符串 - 2

    有没有一种简单的方法可以将给定的整数格式化为具有固定长度和前导零的字符串?#convertnumberstostringsoffixedlength3[1,12,123,1234].map{|e|???}=>["001","012","123","234"]我找到了解决方案,但也许还有更聪明的方法。format('%03d',e)[-3..-1] 最佳答案 如何使用%1000而不是进行字符串操作来获取最后三位数字?[1,12,123,1234].map{|e|format('%03d',e%1000)}更新:根据theTinMan的

  3. ruby-on-rails - 使用 javascript 更改数据方法不会更改 ajax 调用用户的什么方法? - 2

    我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的

  4. ruby - 在 ruby​​ 中使用 .try 函数和 .map 函数 - 2

    我需要从json记录中获取一些值并像下面这样提取curr_json_doc['title']['genre'].map{|s|s['name']}.join(',')但对于某些记录,curr_json_doc['title']['genre']可以为空。所以我想对map和join()使用try函数。我试过如下curr_json_doc['title']['genre'].try(:map,{|s|s['name']}).try(:join,(','))但是没用。 最佳答案 你没有正确传递block。block被传递给参数括号外的方法

  5. ruby-on-rails - 使用 gmaps4rails 动态加载谷歌地图标记 - 2

    如何只加载map边界内的标记gmaps4rails?当然,在平移和/或缩放后加载新的。与此直接相关的是,如何获取map的当前边界和缩放级别? 最佳答案 我是这样做的,我只在用户完成平移或缩放后替换标记,如果您需要不同的行为,请使用不同的事件监听器:在你看来(index.html.erb):{"zoom"=>15,"auto_adjust"=>false,"detect_location"=>true,"center_on_user"=>true}},false,true)%>在View的底部添加:functiongmaps4rail

  6. ruby - 不能将 `each` 的所有或大多数情况替换为 `map` 吗? - 2

    Enumerable#each和Enumerable#map的区别在于返回的是接收者还是映射后的结果。回到接收者是微不足道的,你通常不需要在each之后继续一个方法链,比如each{...}.another_method(我可能没见过这样的案例。即使你想回到接收者那里,你也可以通过tap来实现)。所以我认为所有或者大部分使用Enumerable#each的情况都可以用Enumerable#map代替。我错了吗?如果我是对的,each的目的是什么?map是否比each慢?编辑:我知道当您对返回值不感兴趣时​​使用each是一种常见的做法。我对这种做法是否存在不感兴趣,但感兴趣的是,除了从

  7. ruby - 我可以从 Ruby 中的系统调用中获得连续输出吗? - 2

    当您在Ruby脚本中使用系统调用时,您可以像这样获得该命令的输出:output=`ls`putsoutput这就是thisquestion是关于。但是有没有办法显示系统调用的连续输出?例如,如果您运行此安全复制命令,以通过SSH从服务器获取文件:scpuser@someserver:remoteFile/some/local/folder/...它显示随着下载进度的连续输出。但是这个:output=`scpuser@someserver:remoteFile/some/local/folder/`putsoutput...不捕获该输出。如何从我的Ruby脚本中显示正在进行的下载进度?

  8. ruby - 在 Mechanize 中使用 JavaScript 单击链接 - 2

    我有这个:AccountSummary我想单击该链接,但在使用link_to时出现错误。我试过:bot.click(page.link_with(:href=>/menu_home/))bot.click(page.link_with(:class=>'top_level_active'))bot.click(page.link_with(:href=>/AccountSummary/))我得到的错误是:NoMethodError:nil:NilClass的未定义方法“[]” 最佳答案 那是一个javascript链接。Mechan

  9. ruby-on-rails - 将 Ruby 代码和文字标记与 Haml 混合 - 2

    如何用HAML编写这个ERB:#OR我可以:=some_ruby_code+":"#and=some_ruby_code%br但我不想在这里连接,我想将它写成内联:(=some_ruby_code):#and(=some_ruby_code)%br 最佳答案 =some_ruby_code+":"-#and=some_ruby_code+""编辑1:我不确定您在寻找什么。你想要其中之一吗?==#{some_ruby_code}:-#and==#{some_ruby_code}或==#{some_ruby_code}:-#and=so

  10. ruby - `map` 比 `each` 快吗? - 2

    map遍历数组是否比each更快?两者有速度差异吗?mapresult=arr.map{|a|a+2}每个result=[]arr.eachdo|a|result.push(a+2)end 最佳答案 我认为是的。我试过这个测试require"benchmark"n=10000arr=Array.new(10000,1)Benchmark.bmdo|x|#Mapx.reportdon.timesdoresult=arr.map{|a|a+2}endend#Eachx.reportdon.timesdoresult=[]arr.each

随机推荐