我正在尝试创建一个HTML文件来显示Google地图。这是我用来完成它的代码。

    <!DOCTYPE html>
    <html>
    <head>
    <title> Map</title>
    </head>
    <body>
    <div id="map-container" class="col-md-6"></div>


    <script src="http://maps.google.com/maps/api/js?sensor=true"></script>
    <script>



  function init_map() {

    var var_location = new google.maps.LatLng(12.989802,80.2487);

    var var_mapoptions = {
      center: var_location,
      zoom: 14
    };

    var var_marker = new google.maps.Marker({
        position: var_location,
        map: var_map,
        title:"Venice"});

    var var_map = new google.maps.Map(document.getElementById("map-container"),
        var_mapoptions);

    var_marker.setMap(var_map);

  }

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

   </script>
  </body>


在此代码中,值,纬度和经度是在js内部手动指定的。但是我希望纬度和经度作为url参数传递。

例如:http://www.smart.com/3.html?q=12.989802,80.2487

这是因为将从应用程序中调用我的网址,并且他们希望将纬度和经度作为参数传递。

最佳答案

您可以编写代码以读取和解析查询字符串。迈克·威廉姆斯(Mike Williams)的Google Maps Javascript API v2教程的Part 20 Passing and receiving parameters就是其中的一种描述(请注意,不建议使用v2并关闭v2,但对v3同样适用)。

example using "q=40.7127837,-74.0059413" (the code snippet doesn't take query parameters)



function init_map() {
  var lat, lng;
  // If there are any parameters at eh end of the URL, they will be in  location.search
  // looking something like  "?q=42,-72"

  // skip the first character, we are not interested in the "?"
  var query = location.search.substring(1);

  // split the rest at each "&" character to give a list of  "argname=value"  pairs
  var pairs = query.split("&");
  for (var i = 0; i < pairs.length; i++) {
    // break each pair at the first "=" to obtain the argname and value
    var pos = pairs[i].indexOf("=");
    var argname = pairs[i].substring(0, pos).toLowerCase();
    var value = pairs[i].substring(pos + 1).toLowerCase();

    // process each possible argname  -  use unescape() if theres any chance of spaces
    if (argname == "q") {
      var coords = value.split(",");
      lat = parseFloat(coords[0]);
      lng = parseFloat(coords[1]);
    }
  }
  var var_location;
  if (isNaN(lat) || isNaN(lng)) {
    var_location = new google.maps.LatLng(12.989802, 80.2487);
  } else {
    var_location = new google.maps.LatLng(lat, lng);
  }
  var var_mapoptions = {
    center: var_location,
    zoom: 14
  };

  var var_marker = new google.maps.Marker({
    position: var_location,
    map: var_map,
    title: "Venice"
  });

  var var_map = new google.maps.Map(document.getElementById("map-container"),
    var_mapoptions);

  var_marker.setMap(var_map);

}

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

html,
body,
#map-container {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-container" class="col-md-6"></div>

关于javascript - 在网址中传递纬度和经度作为参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34962648/

10-11 18:10