【问题标题】:Marking several locations with Google Map's geolocate使用 Google Maps 地理定位标记多个位置
【发布时间】:2018-08-10 16:48:14
【问题描述】:

我设置了一个地图,以及一堆类类型为“locs”的 HTML 元素。我想遍历这些,并用标记在谷歌地图上标记它们。但是,任何标记多个的尝试都会失败。有什么帮助或指导吗?这是我当前的代码:

编辑:这是控制台日志:

test.php:68 Uncaught ReferenceError: google is not defined
at test.php:68
jquery.min.js:2 Uncaught TypeError: Cannot read property 'geocode' of 
undefined
    at codeAddress (test.php:36)
    at HTMLOptionElement.<anonymous> (test.php:52)
    at Function.each (jquery.min.js:2)
    at r.fn.init.each (jquery.min.js:2)
    at HTMLDocument.<anonymous> (test.php:50)
    at j (jquery.min.js:2)
    at k (jquery.min.js:2)
js?key=KEY_HERE&callback=initMap:100 
Uncaught Lb

编辑#2:这是完整的代码:

    <?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$events = json_decode(file_get_contents('https://data.melbourne.vic.gov.au/resource/5vsv-f73x.json?$$app_token=KEY_HERE'), true);
$counter = 0;

$seats = json_decode(file_get_contents('https://data.melbourne.vic.gov.au/resource/w4fc-iq27.json?$$app_token=KEY_HERE'), true);


?>

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        var geocoder;
        var map;
        function initialize() {
            geocoder = new google.maps.Geocoder();
            var latlng = new google.maps.LatLng(-34.397, 150.644);
            var mapOptions = {
                zoom: 15,
                center: latlng
            }
            map = new google.maps.Map(document.getElementById('map'), mapOptions);
        }

        function codeAddress(big) {
            var address = big + ", Melbourne";

            geocoder.geocode({'address': address}, function (results, status) {
                if (status == 'OK') {
                    map.setCenter(results[0].geometry.location);
                    var marker = new google.maps.Marker({
                        map: map,
                        position: results[0].geometry.location
                    });
                } else {
                    alert('Geocode was not successful for the following reason: ' + status);
                }
            });

        }
        $(document).ready(function() {


            $('.locs').each(function () {
                alert($(this).text());
                codeAddress($(this).text());
            });
        });




        var arse;
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                var pos = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };


                arse = new google.maps.Marker({
                    position: new google.maps.LatLng(pos['lat'], pos['lng']),
                    map: map,
                    icon: 'https://rnr30-compgroup.netdna-ssl.com/wp-content/themes/rnr3/img/distance_marker.png'
                });

                map.setCenter(pos);
                map.setZoom(12);

                var cityCircle = new google.maps.Circle({
                    strokeColor: '#FF0000',
                    strokeOpacity: 0.8,
                    strokeWeight: 2,
                    fillColor: '#FF0000',
                    fillOpacity: 0.35,
                    map: map,
                    center: pos,
                    radius: 10000
                });

            }, function() {
            });
        } else {
            // Browser doesn't support Geolocation
        }
    </script>
    <style>
        #map {
            height: 400px;
            width: 100%;
        }
    </style>
</head>
<body onload="initialize()">
<div id="map" style="width: 320px; height: 480px;"></div>

<?php
echo "<select id='loc' onchange='codeAddress()'>";
foreach($events as $event)
{
    //print_r($event);
    echo "<option class='locs' value='loc".$counter."'>".$event['location']."</div> <br>";
    $counter++;
}
echo "</select>";
?>
</body>
<script async defer
        src="https://maps.googleapis.com/maps/api/js?key=KEY_HERE&callback=initMap">
</script>
</body>
</html>

【问题讨论】:

  • 什么是控制台错误?如果你把 html 放在这里会更好。
  • 控制台有错误吗?
  • 您的 html 无效 - 两个结束 &lt;/body&gt; 标记
  • 加载 google api 时调用的回调被称为 initMap 而你初始化地图的函数被称为 initialize
  • @PL200 codeAddress 在谷歌库加载之前被调用。请检查

标签: javascript php google-maps google-maps-api-3 maps


【解决方案1】:

原始代码中有很多问题阻止了它工作 - 我认为它会很快超过每日查询限制。但是,我在这里稍微修改了代码流程,目前遍历每个位置的例程在第一个地址之后终止(这是为了测试而故意)

我将这段代码放在navigator.geolocation 回调中,尽管它可以在initialize 函数中轻松完成。

顺便说一句——在那个循环中使用alert 语句是一个非常痛苦的****——需要很长时间才能完成整个过程! ;(

目前这成功地对第一个地址进行了地理编码并添加了一个标记 - 但是,正如我所说,代码在第一次输入后故意终止。

<?php
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);

    $counter = 0;
    $events = json_decode( file_get_contents( 'http://data.melbourne.vic.gov.au/resource/5vsv-f73x.json?$$app_token=RI7KnTt7JLb6dtsY4jiCET3Qq' ), true);
    $seats = json_decode( file_get_contents( 'http://data.melbourne.vic.gov.au/resource/w4fc-iq27.json?$$app_token=RI7KnTt7JLb6dtsY4jiCET3Qq' ), true );


?>

<!DOCTYPE html>
<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        var geocoder;
        var map;


        function initialize() {
            geocoder = new google.maps.Geocoder();
            var latlng = new google.maps.LatLng(-34.397, 150.644);
            var mapOptions = {
                zoom: 15,
                center: latlng
            }
            map = new google.maps.Map(document.getElementById('map'), mapOptions);



            var mkr;
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {
                    var pos = {
                        lat: position.coords.latitude,
                        lng: position.coords.longitude
                    };


                    mkr = new google.maps.Marker({
                        position: new google.maps.LatLng(pos['lat'], pos['lng']),
                        map: map,
                        icon: 'https://rnr30-compgroup.netdna-ssl.com/wp-content/themes/rnr3/img/distance_marker.png'
                    });

                    map.setCenter(pos);
                    map.setZoom(12);

                    var cityCircle = new google.maps.Circle({
                        strokeColor: '#FF0000',
                        strokeOpacity: 0.8,
                        strokeWeight: 2,
                        fillColor: '#FF0000',
                        fillOpacity: 0.35,
                        map: map,
                        center: pos,
                        radius: 10000
                    });



                    console.clear();
                    $('.locs').each(function() {
                        codeAddress( $(this).text() );
                        console.info( $(this).text() );
                        return false;/* remove this `return false;` statement to proceed with ALL requests ... warning!*/
                    });

                }, function( err ) {
                    console.warn( err )
                });
            } else {
                // Browser doesn't support Geolocation
            }
        }

        function codeAddress(big) {
            var address = big + ", Melbourne";

            geocoder.geocode({'address': address}, function (results, status) {
                if (status == 'OK') {
                    map.setCenter(results[0].geometry.location);
                    var marker = new google.maps.Marker({
                        map: map,
                        position: results[0].geometry.location
                    });
                } else {
                    console.log('Geocode was not successful for the following reason: ' + status);
                }
            });
        }

    </script>
    <style>
        #map {
            height: 400px;
            width: 100%;
        }
    </style>
</head>
<body onload="initialize()">
    <div id="map" style="width: 320px; height: 480px;"></div>

    <?php
        echo "<select id='loc' onchange='codeAddress(this.options[ this.options.selectedIndex ].text)'>";
        foreach( $events as $event ){
            echo "<option class='locs' value='loc".$counter."'>".$event['location']."</div> <br>";
            $counter++;
        }
        echo "</select>";
    ?>

    <script async defer src="//maps.googleapis.com/maps/api/js?key=AIzaSyCaZxKJmzB3sbIE72rQ_No-xQVP5YwOxjU&callback=initialize"></script>
</body>
</html>

【讨论】:

  • 干得好,你做的比我要求的要多得多。代码很丑,因为我试图用以前项目的代码快速敲出一些东西。非常感谢,让我意识到我的错误!
猜你喜欢
  • 1970-01-01
  • 2012-01-06
  • 1970-01-01
  • 1970-01-01
  • 2018-12-20
  • 1970-01-01
  • 1970-01-01
  • 2016-11-06
  • 2016-11-29
相关资源
最近更新 更多