【问题标题】:Google Maps adjusting to include users and address谷歌地图调整以包括用户和地址
【发布时间】:2019-11-19 21:45:49
【问题描述】:

我正在尝试对代码进行一些调整,但开发人员无法再提供帮助。我对 GMaps api 和代码一无所知,但我仍在试图弄清楚。

问题是我们在地图上有用户,我们希望地图自动放大以包含所有用户。这是我们能够做到的。但是,我们有一个应该包含在其中的主地址......所以我们想要做的是自动缩放到足够近以包括最远点,无论是用户还是主地址。为了演示,请看下面的 URL:

http://app2.wehaveeyes.com/reports/maps/maps2.cfm

如果缩小,您会看到主要地址大约在 5 英里之外。

但这是我们希望它自动缩放以包含主要地址

下面是代码:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <META HTTP-EQUIV="refresh" CONTENT="10">

    <style>
        /* Set the size of the div element that contains the map */
        #map {
            height: 100%;  /* The height is the height of the web page */
            width: 100%;  /* The width is the width of the web page */
        }

        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
        }

        .user_info {
            background-color: ##0000;
            font-weight: bold;
            color: #fff;
        }
    </style>

    <script src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY">      
  </script>
    <script src="https://cdn.sobekrepository.org/includes/gmaps-markerwithlabel/1.9.1/gmaps-   
 markerwithlabel-1.9.1.js" type="text/javascript"></script>
</head>
<body>
    <div id="map"></div>

    <script type="text/javascript">
        // Initialize and add the map
        function initMap() {
            var xml_data = "<MAP>" + 
                    "<location>1 South Main Street, Akron Ohio</location>" + 
                    "<user_info>" + 
                    "<user_name>Scott jones</user_name>" + 
                    "<user_lat>41.141756</user_lat>" + 
                    "<user_lon>-81.675599</user_lon>" + 
                    "<user_img>https://s3.amazonaws.com/media.wbur.org/wordpress/1/files/2015/03/AP736858445562.jpg</user_img>" +
                    "</user_info>" + 
                    "<user_info>" + 
                    "<user_name>Bill James</user_name>" + 
                    "<user_lat>41.142758</user_lat>" + 
                    "<user_lon>-81.657274</user_lon>" + 
                    "<user_img>https://s.abcnews.com/images/US/jeff-koenig-ht-ml-190122_hpEmbed_2_4x5_992.jpg</user_img>" + 
                    "</user_info>" + 
                    "<user_info>" + 
                    "<user_name>Karrie Sims</user_name>" + 
                    "<user_lat>41.135809</user_lat>" + 
                    "<user_lon>-81.639336</user_lon>" + 
                    "<user_img>https://www.odmp.org/media/image/officer/23891/orig/police-officer-natalie-corona.jpg</user_img>" + 
                    "</user_info>" + 
                    "<user_info>" + 
                    "<user_name>John Smith</user_name>" + 
                    "<user_lat>41.142855</user_lat>" + 
                    "<user_lon>-81.637319</user_lon>" + 
                    "<user_img>https://www.odmp.org/media/image/officer/24262/400/deputy-sheriff-jake-allmendinger.jpg</user_img>" + 
                    "</user_info>" + 
                    "<user_info>" + 
                    "<user_name>Jim Deek</user_name>" + 
                    "<user_lat>41.131543</user_lat>" + 
                    "<user_lon>-81.653541</user_lon>" + 
                    "<user_img>https://lawofficer.com/wp-content/uploads/2016/10/blakesnyder.jpg</user_img>" + 
                    "</user_info>" + 
                    "</MAP>";

            var parser = new DOMParser();
            var xmlDoc = parser.parseFromString(xml_data, "text/xml");
            var address = xmlDoc.getElementsByTagName("location")[0].textContent;
            var users = xmlDoc.getElementsByTagName("user_info");
            var user_list = [];

            for (var i = 0; i < users.length; i++) {
                user_list.push({
                    "name": users[i].getElementsByTagName("user_name")[0].textContent,
                    "lat": users[i].getElementsByTagName("user_lat")[0].textContent,
                    "lng": users[i].getElementsByTagName("user_lon")[0].textContent,
                    "img": users[i].getElementsByTagName("user_img")[0].textContent
                });
            }

            // The location of US
            var map_center = {lat: 39.8283, lng: -98.5795};
            // The map, centered at US
            var map = new google.maps.Map(document.getElementById('map'), {zoom: 3, center: map_center});

            // boundary of all pins
            var bounds = new google.maps.LatLngBounds();

            // converts address into geolocation with lat and lng
            geocoder = new google.maps.Geocoder();
            codeAddress(geocoder, map, address);

            // adds user_info marker
            for (const index in user_list) {
                lat = parseFloat(user_list[index]["lat"]);
                lng = parseFloat(user_list[index]["lng"]);

                var point = {lat: lat, lng: lng}
                var lbl_content = "<div style='text-align: center;'><div><img src='" + 
                        user_list[index]["img"] + 
                        "' width='30px' height='38px' style='border: 2px solid #000; display: block; margin: 0 auto;'></div>" + 
                        "<div style='background-color: #000; padding: 2px;'>" + 
                        user_list[index]["name"] + 
                        "</div></div>";
                var marker = new MarkerWithLabel({
                    position: point,
                    icon: {
                        url: "./res/police_pin.png",
                        scaledSize: new google.maps.Size(40, 40)
                    },
                    map: map,
                    title: user_list[index]["name"],
                    labelContent: lbl_content,
                    labelAnchor: new google.maps.Point(0, 0),
                    labelClass: "user_info",
                    labelInBackground: true
                });

                // extends boundary
                bounds.extend(point);

                // shows coordinate tooltip with 4-decisions
               // var infowindow = new google.maps.InfoWindow({
                //    content: lat.toFixed(4) + ", " + lng.toFixed(4)
               // });
               // infowindow.open(map, marker);
            }

            // fits map
            map.fitBounds(bounds);
        }

        /////////////////////////////////////////
        /// converts address into geolocation ///
        /////////////////////////////////////////
        function codeAddress(geocoder, map, address) {
            geocoder.geocode({'address': address}, function (results, status) {
                if (status === 'OK') {
                    // relocates the map centered at address pin
    //                        map.setCenter(results[0].geometry.location);

                    var marker = new google.maps.Marker({
                        map: map,
                        position: results[0].geometry.location,
                        icon: {url: "./res/911_call.png", scaledSize: new google.maps.Size(55, 55)}
                    });

                    // shows coordinate tooltip with 4-decisions
                    //lat = results[0].geometry.location.lat();
                    //lng = results[0].geometry.location.lng();
                    //var infowindow = new google.maps.InfoWindow({
                    //    content: lat.toFixed(4) + ", " + lng.toFixed(4)
                    //});
                    //infowindow.open(map, marker);
                } else {
                    alert('Geocode was not successful for the following reason: ' + status);
                }
            });
        }

        ////////////////////////////
        /// reads local xml file ///
        ////////////////////////////
        function readTextFile(file)
        {
            var allText = "";
            var rawFile = new XMLHttpRequest();
            rawFile.open("GET", file, false);
            rawFile.onreadystatechange = function ()
            {
                if (rawFile.readyState === 4)
                {
                    if (rawFile.status === 200 || rawFile.status == 0)
                    {
                        allText = rawFile.responseText;
                    }
                }
            }
            rawFile.send(null);
            return allText;
        }

        initMap();
    </script>
  </body>
 </html>

我浏览了很多板并尝试使用代码,但没有任何效果。任何帮助都会很棒。

非常感谢!!!

【问题讨论】:

  • 使您的函数codeAddress 返回地址的地理编码位置,并对该地址执行与其他点相同的bounds.extend(foo)
  • 谢谢。我会试试看。那么您是说某种意义上的地址与用户标记相结合吗?
  • 有点——关键是你目前正在为所有用户点做bounds.extend(point);但是您没有使用 911 点来扩展界限。您可以将它们组合起来,或者您可以单独在 911 点上运行该功能。
  • 非常感谢。我一定会试一试的!!!感谢您的帮助!
  • 再次感谢字母汤!从编码的角度来看,您对如何编辑代码有什么建议吗?当涉及到 Google API 代码时,我很糟糕,最终破坏的比我修复的要多。任何帮助将不胜感激。

标签: javascript api google-maps gis


【解决方案1】:

要确保地图视口中的每个重要位置都被覆盖,您可以使用map.fitBounds() 方法。按照这个doc,这个方法

设置视口以包含给定的边界。

我看到您已经实现了这个方法来显示每个用户。也就是说,您只需在边界上添加(您所称的)main address

要将主地址的坐标添加到边界实例,您只需使用bounds.extend() 方法。

我检查了site 上的代码,您可以这样做:

  1. 将变量 bounds 移动到您的 initMap() 函数上方,将其设为全局变量。
  2. 在您的codeAddress() 函数中,通过扩展bounds 添加main address' 坐标。这是一个代码sn-p:

    // Add the main address' coordinates by using bounds.extend method
    // results[0].geometry.location contains the main address' coordinates
    bounds.extend(results[0].geometry.location);
    
  3. map.fitBounds() 方法移到步骤#2 的bounds.extend() 方法下方。

    // fits map
    map.fitBounds(bounds);
    

这是一个基于您的代码的有效fiddle

【讨论】:

    猜你喜欢
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    相关资源
    最近更新 更多