php - 尝试在php中动态创建一个纬度和经度数组

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

我正在尝试使用我在 mySQL 数据库中的城市创建一个纬度和经度数组。这是我到目前为止所拥有的。我正在尝试在 javascript 中设置数组变量,并回显其中的字段。读取“markers”数组,使标记出现在谷歌地图上所需的位置:

编辑:这是整个脚本

<script type="text/javascript">

var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();

    var mapOptions = {
    zoom: 5,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('map_canvas'),
                              mapOptions);
    directionsDisplay.setMap(map);

    var markers = [

    <?php

    //orgnize fans by city
    $query = "SELECT city, state, COUNT(*) fans FROM users GROUP BY city ORDER BY fans DESC";
    $result = mysql_query($query) or die(mysql_error());
    while($row = mysql_fetch_array($result)){

    //pulls the city, state code from the database and stores it as a string in $address
    $address = urlencode('"' . $row['city'] . ", " . $row['state'] . '"');
    $googleApi = 'http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false';     

    $json = file_get_contents(sprintf($googleApi, $address));   
    $resultObject = json_decode($json);

    $location = $resultObject->results[0]->geometry->location;

    $lat = $location->lat;
    $lng = $location->lng;

        echo "{ lat: ".$lat.", lng: ".$lng.", name: ".'"'.$row['city'].", ".$row['state'].'"'."},";
    }

    ?>

    ];

    // Create the markers ad infowindows.
    for (index in markers) addMarker(markers[index]);
    function addMarker(data) {
        // Create the marker
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(data.lat, data.lng),
            map: map,
            title: data.name
        });

        // Create the infowindow with two DIV placeholders
        // One for a text string, the other for the StreetView panorama.
        var content = document.createElement("DIV");
        var title = document.createElement("DIV");
        title.innerHTML = data.name;
        content.appendChild(title);
        var streetview = document.createElement("DIV");
        streetview.style.width = "200px";
        streetview.style.height = "200px";
        content.appendChild(streetview);
        var infowindow = new google.maps.InfoWindow({
            content: content
        });

        // Open the infowindow on marker click
        google.maps.event.addListener(marker, "click", function() {
            infowindow.open(map, marker);
        });

        // Handle the DOM ready event to create the StreetView panorama
        // as it can only be created once the DIV inside the infowindow is loaded in the DOM.
        google.maps.event.addListenerOnce(infowindow, "domready", function() {
            var panorama = new google.maps.StreetViewPanorama(streetview, {
            navigationControl: false,
            enableCloseButton: false,
            addressControl: false,
            linksControl: false,
            visible: true,
            position: marker.getPosition()
            });
       });

    }

    // Try HTML5 geolocation
    if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            var pos = new google.maps.LatLng(position.coords.latitude,
            position.coords.longitude);

            var infowindow = new google.maps.InfoWindow({
            map: map,
            position: pos,
            content: 'Your Current City'
        });

            map.setCenter(pos);
        }, function() {
        handleNoGeolocation(true);
        });

    } else {
        // Browser doesn't support Geolocation
        handleNoGeolocation(false);
    }

}

function handleNoGeolocation(errorFlag) {
    if (errorFlag) {
        var content = 'Error: The Geolocation service failed.';
    } else {
        var content = 'Error: Your browser doesn\'t support geolocation.';
    }

    var options = {
    map: map,
    position: new google.maps.LatLng(60, 105),
    content: content
    };

    var infowindow = new google.maps.InfoWindow(options);
    map.setCenter(options.position);
}


function calcRoute() {
    var start = document.getElementById('start').value;
    var end = document.getElementById('end').value;
    var waypts = [];
    var checkboxArray = document.getElementById('waypoints');
    for (var i = 0; i < checkboxArray.length; i++) {
        if (checkboxArray.options[i].selected == true) {
            waypts.push({
                        location:checkboxArray[i].value,
                        stopover:true});
        }
    }

    var request = {
    origin: start,
    destination: end,
    waypoints: waypts,
    optimizeWaypoints: true,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
                            if (status == google.maps.DirectionsStatus.OK) {
                            directionsDisplay.setDirections(response);
                            var route = response.routes[0];
                            var summaryPanel = document.getElementById('directions_panel');
                            summaryPanel.innerHTML = '';
                            // For each route, display summary information.
                            for (var i = 0; i < route.legs.length; i++) {
                            var routeSegment = i + 1;
                            summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
                            summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
                            summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
                            summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
                            }
                            }
                            });
}

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


</script>

当我打开 html 时,我调用初始化并制作 Canvas :

<body onload="initialize()">

<div id="map_canvas" style="width: 1100px; height: 450px;">map div</div>

最佳答案

您有一个错字:有时您使用 long,而在其他时候使用 lng

在代码段中:

var marker = new google.maps.Marker({
        position: new google.maps.LatLng(data.lat, data.lng),
        map: map,
        title: data.name
    });}

在你之前使用

$lng = $location->lng;
echo "{ lat: ".$lat.", lng: ".$long.", name: ".'"'.$row['city'].", ".$row['state'].'"'."},";

实际上,应该在数组中生成经度的 echo 语句引用了一个未初始化的变量 $long。解决这个问题,你应该可以开始了。换句话说,改变

$lng = $location->lng;

$long = $location->lng;

(或更改您的 echo 语句...)

关于php - 尝试在php中动态创建一个纬度和经度数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14618792/

相关文章:

javascript - Redux 的第一步。如何给mapStateToProps添加值?

javascript - 用于检查未定义值的优雅 Javascript 代码

mysql: 恰好语句 "Start binlog_dump to slave_server"登录到master错误日志

php - 使用 php 和 mysql 从用户的所有好友检索用户个人资料数据

php - AWS S3 - 使用 PHP SDK2 设置元数据

PHP:更改密码

javascript - 使用 angularJs 单击时更改图标

MySQL:数据库名称作为 View 中的参数

PHP mail() - 如何设置优先级?

php - Jquery影子框冲突