如何在地图上设置当前位置中心?

时间:2015-03-28 20:23:00

标签: javascript html google-maps

我尝试了在本网站和网站上找到的不同方法,但它们对我不起作用(

这是我的代码:

<h:panelGroup id="GMWrapper" style="background-color: red">
  <p:gmap widgetVar="mainMap" center="49.835, 24.0083" zoom="15"
          id="mainGoogleMap" type="HYBRID"
          style="width: 600px; height: 400px" model="#{userPlaces.model}"
          styleClass="gmappStyle" onPointClick="handlePointClick(event)" />
  <p:commandButton onclick="someFunc()"></p:commandButton>
  <script type="text/javascript">
    function someFunc() {
      if (navigator.geolocation) {
        alert("Start")
        navigator.geolocation
        .getCurrentPosition(success);
        alert("Successful!")
        var elem = document
        .getElementById("mainGoogleMap");
        alert("Element was find")
        elem.setCenter(new google.maps.LatLng(37.4419, -122.1419));
        alert("Good done!");
      } else {
        error('Geo Location is not supported');
        currentLat = 0.0;
        currentLng = 0.0;
      }
    }

    var currentLat;
    var currentLng;

    function success(position) {
      currentLat = position.coords.latitude;
      currentLng = position.coords.longitude;
    }
  </script>
</h:panelGroup>

Javascript代码适用于alert("Element was find")

我也试过了:

elem.setAttribute("center", currentLat.toString() + ", " + currentLng.toString()); elem.setAttribute("center", currentLat + ", " + currentLng); elem.setAttribute("center", "37.4419, -122.1419"); 还有其他一些..

1 个答案:

答案 0 :(得分:0)

从谷歌地图文档:panTo(latLng:LatLng | LatLngLiteral) - 将地图的中心更改为给定的LatLng。如果更改小于地图的宽度和高度,则过渡将平滑地动画。下面是一个片段,用于创建地图并将地图置于某个位置。

<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
    <script>
var map;
function initialize() {
  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644)
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);
  map.panTo(new google.maps.LatLng(37.4419, -122.1419));
}

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

    </script>
  </head>
  <body>
    <div id="map-canvas"></div>
  </body>
</html>