谷歌地图lat lat long array

时间:2017-05-02 13:15:53

标签: php google-maps

我有两个数组$lat$long

1   "73.0785729"
2   "73.0785729"
3   "73.0785729"

$long相同。

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

function init() {
    var mapOptions = {
        zoom: 11,
        center: new google.maps.LatLng(40.6700, -73.9400),
        styles: []
    };
    var mapElement = document.getElementById('map');
    var map = new google.maps.Map(mapElement, mapOptions);
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng({{$lat}}, {{$long}}),
        map: map,
        title: 'Snazzy!'
    });
}

抛出htmlspecialchars() expects parameter 1 to be string, array given

2 个答案:

答案 0 :(得分:1)

您必须使用json_encode将您的PHP数据传递给Javascript:

<?php

//Construct the array you want, assuming $lat and $long have the same length
$markers = array();
foreach($lat as $i => $currentLat) {
    $markers[] = array("lat" => $currentLat, "long" => $long[$i]);
}

并修改你的Javascript:

function init() {
    var mapOptions = {
        zoom: 11,
        center: new google.maps.LatLng(40.6700, -73.9400),
        styles: []
    };
    var mapElement = document.getElementById('map');
    var map = new google.maps.Map(mapElement, mapOptions);
    var markers = <?php echo json_encode($markers); ?>; //Passing the PHP values to JS

    //Add marker to map
    for(var i in markers) {
        var marker = markers[i];
        new google.maps.Marker({
            position: new google.maps.LatLng(marker.lat, marker.long),
            map: map,
            title: 'Snazzy!'
        });
    }
}

答案 1 :(得分:0)

        <?php
            $lat = ['73.0785729','73.0785729','73.0785729'];
            $long = ['73.0785729', '73.0715769', '73.0785729'];
        ?>

        var lat_array = <?=json_encode($lat)?>;
        var long_array = <?=json_encode($long)?>;

        function init() {
            var mapOptions = {
                zoom: 11,
                center: new google.maps.LatLng(40.6700, -73.9400),
                styles: []
            };
            var mapElement = document.getElementById('map');
            var map = new google.maps.Map(mapElement, mapOptions);

            // assuming that the length of lat_array and long_array are the same
            for(var i = 0; i < lat_array.length; i++){
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(parseFloat(lat_array[i]), parseFloat(long_array[i])),
                    map: map,
                    title: 'Snazzy!'
                });
            }

        }