【问题标题】:update google map position via javascript通过javascript更新谷歌地图位置
【发布时间】:2014-06-24 04:15:04
【问题描述】:

我可以更新谷歌地图标记位置,但我无法更新谷歌地图位置。它不会将地图居中到给定的经纬度位置

var myLatlng;
var map;
var infowindow;
var latitude;
var longtitude;
var marker;

loadMap();
function loadMap()
{
    myLatlng = new google.maps.LatLng(54.91252, -1.37664);

    var mapOptions = {
        zoom: 17,
        center: myLatlng
    };

    map = new google.maps.Map(document.getElementById("googlemaps"), mapOptions);
    var contentString = '<h5>The Mew </h5>';

    infowindow = new google.maps.InfoWindow({
        content: contentString
    });

    marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title: "The Mew",
        animation: google.maps.Animation.DROP
    });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map, marker);
    });
    infowindow.open(map, marker);
}

function updatePosition()
{
    latitude = document.getElementById('latitude');
    longtitude = document.getElementById('longtitude');
    myLatlng = new google.maps.LatLng(latitude, longtitude);
    marker.setPosition(myLatlng);
    map.setCenter(myLatlng);
}



  <input type="text" id="latitude" />
   <input type="text" id="longtitude" />
   <a onclick="updatePosition()" >update </a>

【问题讨论】:

  • @edcs 请阅读这个问题。他们是不同的问题
  • 不要直接打电话给loadMap。而是为要加载的窗口添加一个谷歌事件监听器,然后调用它:google.maps.event.addDomListener(window, 'load', loadMap);

标签: javascript google-maps google-maps-api-3


【解决方案1】:

updatePosition 中,您分配给纬度和经度的信息是这些输入字段的 DOM 节点,但您想要分配这些输入的 .此外,您需要确保将您从这些值中获取的 text 转换为 number 以便LatLng 正确接受它们。您可以为此使用parseInt。不要忘记基数。

function updatePosition() {
  latitude = parseInt(document.getElementById('latitude').value, 10);
  longtitude = parseInt(document.getElementById('longtitude').value, 10);
  myLatlng = new google.maps.LatLng(latitude, longtitude);
  marker.setPosition(myLatlng);
  map.setCenter(myLatlng);
}

【讨论】:

    【解决方案2】:

    您可以使用 jQuery 获取输入值

    function updatePosition()
     {
       var lat= $('#latitude').val();
       var lng= $('#longtitude').val();
       myLatlng = new google.maps.LatLng(lat,lng);
       marker.setPosition(myLatlng);
       map.setCenter(myLatlng);
     } 
    

    在 Javascript 中你必须使用 parseInt 来解析字符串并返回一个整数

      lat = parseInt(document.getElementById('latitude').value,10);
      lng = parseInt(document.getElementById('longtitude').value,10); 
    

    FIDDLE DEMO

    【讨论】:

    • 如果 OP 没有在代码的其他任何地方使用 jQuery,他们为什么要在这里使用它?
    • JQuery 只是一个特定的 JavaScript 代码库,它非常易于使用且功能强大。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    相关资源
    最近更新 更多