使用javascript从pin中心谷歌地图

时间:2013-04-26 04:22:37

标签: javascript google-maps

我有我的页面,以便用户可以看到他们的纬度和经度。我已经嵌入了谷歌地图,以便用户可以实际查看他们所处的位置。这是我的计算机科学课程的一个项目,所以我不希望你为我编写代码。我只是想知道如何解决这个问题。这就是我现在所拥有的。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />

    <!-- This page will allow the suer to track their location through means of the HTML5 Geolocation feature -->

    <title>Assignment 4:Track My Location</title>
    <meta name="author" content="Alan Sylvestre" />

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

    <script>
        function myLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(locationReveal);
            } else {
                alert("Please use a different browser that supports geolocation.");
            }
        }


        window.onload = myLocation;

        function locationReveal(position) {
            showMap(position.coords);
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            var div = document.getElementById("location");
            div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;
        }

        var map;
        function showMap(coords) {
            var googleLatAndLong = new google.maps.LatLng(coords.latitude, coords.longitude);
            var mapOptions = {
                zoom : 18,
                center : googleLatAndLong,
                mapTypeId : google.maps.MapTypeId.SATELLITE
            };
            var mapDiv = document.getElementById("map");
            map = new google.maps.Map(mapDiv, mapOptions);
            addMarker(googleLatAndLong);

        }


        google.maps.Map(mapDiv, mapOptions);

        var marker;
        function addMarker(latlong) {
            var markerOptions = {
                position : latlong,
                map : map
            };
            marker = new google.maps.Marker(markerOptions);
        }

        var center;
        function calculateCenter() {
            center = map.getCenter();
        }

    </script>

</head>

<body style="background-color:yellow;" text="blue;">
    <div align="center">
        <h1>Reveal My Location</h1>
        <p>
            You know what's pretty cool? Tracking your location using a simple internet connection. By clicking this button, you're browser will track a global database and reveal your location in terms of latitude and longitude. Enjoy!
        </p>
        <div id="location"></div>
        <br>
        <div id="map" style="width:400px; height:400px;"></div>
        <br>
        <input type="button" id="centerOfMap" value="Center" onclick="calculateCenter()">
        <footer>
            <p>
                &copy; Copyright  by Alan Sylvestre
            </p>
        </footer>
    </div>
</body>

1 个答案:

答案 0 :(得分:0)

首先,您需要确保在运行JavaScript之前加载了DOM。

这就是'mapDiv''未定义'的原因。

将您的脚本包装在window.onload匿名函数中,或将其推送到关闭正文标记之前。