user1072337
user1072337

Reputation: 12935

Trying to make an array of latitude and longitudes dynamically in php

I am trying to make an array of latitudes and longitudes using cities that I have in a mySQL database. This is what I have so far. I am trying to set up the array variable in javascript, and echo out the fields inside. The "markers" array is read to make markers appear on the google map at the desired locations:

EDIT: Here is the entire script

<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>

When I open the html, I call initialize and make the canvas:

<body onload="initialize()">

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

Upvotes: 1

Views: 3056

Answers (2)

Floris
Floris

Reputation: 46365

My earlier answer dealt with the typo. I think there's a fundamental issue with "how to draw maps with the google API". The following code snippet (from google JavaScript API shows an example of using overlays (which is what a marker is):

var myLatlng = new google.maps.LatLng(-25.363882,131.044922); 
var mapOptions = {   
    zoom: 4,   
    center: myLatlng,   
mapTypeId: google.maps.MapTypeId.ROADMAP, }

var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var marker = new google.maps.Marker({
     position: myLatlng,
     title:"Hello World!" });  
// To add the marker to the map, call setMap();
marker.setMap(map);

Several of these steps appear to be missing from your code - maybe you didn't show them, or maybe you didn't realize you needed them?

EDIT: even after you posted your full code, I still don't see certain things I would expect.

Here are one thing you can try for sure: call the google API before referencing it: add this line

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"> </script>

right below <head>, before your <script>

Fixing just this, and taking out a bunch of "superfluous" (for the purpose of "getting a map with a pin") lines, allowed me to create a simple file that can render a map of New York, NY with one marker on it. The source code can be found at http://www.floris.us/SO/maptest.php.txt . From there, you can add more stuff back in...

Further edit: with the lessons learnt, I made http://www.floris.us/SO/maptestFull.php which has most of the functionality you were looking for (not the DB lookup, which I don't have, obviously). Once again, source code is copied in .php.txt file so you can look at it. Slightly messy (from trying to turn things on/off) - you will have to look closely to see all the changes I made.

Upvotes: 0

Floris
Floris

Reputation: 46365

You have a typo: sometimes you use long, at other times lng.

in the code segment:

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

while earlier you use

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

In effect, your echo statement, which should be producing longitudes in your array, is referencing a non-initialized variable, $long. Fix that and you should be good to go. In other words, change

$lng = $location->lng;

to

$long = $location->lng;

(or change your echo statement...)

Upvotes: 1

Related Questions