首页 > 解决方案 > 根据我自己的位置居中标记时出错

问题描述

我一直在尝试将标记集中在用户位置(地理位置)上,但我遇到了这种类型的错误:Uncaught TypeError: Cannot read property 'setPosition' of undefined at showPosition。我错过了什么或做错了什么?我希望有人可以帮助我。这是我的 JavaScript 代码:

var map;
var infoWindow = new google.maps.InfoWindow();
var x = document.getElementById("geoLocation");
function getLocation() {
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
} else {
    x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
        var pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };

        infoWindow.setPosition(pos);
        infoWindow.setContent('This is your location.');
        infoWindow.open(map);
        map.setCenter(pos);
x.innerHTML = "Latitude: " + (position.coords.latitude).toFixed(6) + 
"<br>Longitude: " + (position.coords.longitude).toFixed(6);
}


  function initMap() {
    var bamako = new google.maps.LatLng(12.6425212, -8.0099928),
    map = new google.maps.Map(document.getElementById("map"), {
      center: bamako,
      zoom: 16
    }),
    marker = new google.maps.Marker({position: bamako, map: map});
    google.maps.event.addListener(map, "mousemove", function (e) {
    var t = e.latLng;
    document.getElementById("mlat").innerHTML = "(" + t.lat().toFixed(6) + ", " + t.lng().toFixed(6) + ")"
    });
    google.maps.event.addListener(map, "click", function (e) {
    marker.setPosition(e.latLng);
    var t = e.latLng, o = "(" + t.lat().toFixed(6) + ", " + t.lng().toFixed(6) + ")";
    document.getElementById("lat").value = t.lat().toFixed(6), document.getElementById("lng").value = t.lng().toFixed(6);
    });
    getLocation();
  }

HTML 代码:

<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<title>MaliBaGuide</title>
<style>
  /* Always set the map height explicitly to define the size of the div
   * element that contains the map. */
  #map {
    height: 80%;
    width: 70%;
  }
  /* Optional: Makes the sample page fill the window. */
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
</style>
</head>
<body>
<button class="btn btn-success" onclick="getLocation()">Get My 
Position</button>
<h6>GeoLocation Coordinates</h6>
<div id="geoLocation"></div>
<div id="map"></div>
<div class="col-md-8">
  <label for="lat">Latitude</label>
  <input type="text" name="lat" id="lat" placeholder="lat coordinate" />
  <label for="lng">Longitude</label>
  <input type="text" name="lng" id="lng" placeholder="long coordinate" />
  <h3 class="titleh3">Map Mouse Over Location</h3>
  <span id="mlat" class="coordinatetxt">0,0</span>
</div>
<script src="gmap1.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script async defer
src="https://maps.googleapis.com/maps/api/js? 
key=AIzaSyCXZ1ps6lHbElohymJukUi4KOY6g_rjGQ0&callback=initMap">
</script>
</body>
</html>

标签: javascriptgoogle-maps-api-3

解决方案


这意味着您实际上并没有设置infoWindow为任何东西,您只是宣布它存在。JavaScript 解释器告诉您,您不能尝试访问本身尚未定义的内容的属性。

您可以infoWindow通过如下实例化它来正确初始化:

var infoWindow = new google.maps.InfoWindow({});

完整代码(带有一些清理格式):

var map;
var infoWindow;
var x = document.getElementById("geoLocation");

function getLocation() {
        if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showPosition);
        } else {
                x.innerHTML = "Geolocation is not supported by this browser.";
        }
}

function showPosition(position) {
        var pos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
        };

        infoWindow.setPosition(pos);
        infoWindow.setContent('This is your location.');
        infoWindow.open(map);
        map.setCenter(pos);
        x.innerHTML = "Latitude: " + (position.coords.latitude).toFixed(6) + 
        "<br>Longitude: " + (position.coords.longitude).toFixed(6);
}


function initMap() {
    var bamako = new google.maps.LatLng(12.6425212, -8.0099928),
    infoWindow = new google.maps.InfoWindow({});
    map = new google.maps.Map(document.getElementById("map"), {
                center: bamako,
                zoom: 16
    }),
    marker = new google.maps.Marker({position: bamako, map: map});
    google.maps.event.addListener(map, "mousemove", function (e) {
                var t = e.latLng;
                document.getElementById("mlat").innerHTML = "(" + t.lat().toFixed(6) + ", " + t.lng().toFixed(6) + ")"
    });
    google.maps.event.addListener(map, "click", function (e) {
                marker.setPosition(e.latLng);
                var t = e.latLng, o = "(" + t.lat().toFixed(6) + ", " + t.lng().toFixed(6) + ")";
                document.getElementById("lat").value = t.lat().toFixed(6), document.getElementById("lng").value = t.lng().toFixed(6);
    });
    getLocation();
}

推荐阅读