0

I am working on a website in which I am trying to incorporate Google maps. The page fetches values from a database using php. It then passes one of the column values to a javascript function which plots it using Google Maps. Now, I want to display the plots of all the values in a single map.

I am attaching the javascript function and the php call. Here is the code:

<script type="text/javascript">

var myOptions;
var map;
var geocoder;
var first_call = 0;

function map_function(addr){
    // Define the addresses we want to map.
    var clubs = addr;
    // Create a new Geocoder
    if (first_call == 0){
        var geocoder = new google.maps.Geocoder();
    }
    // Locate the address using the Geocoder.
    geocoder.geocode( { "address": clubs }, function(results, status) {
        // If the Geocoding was successful
        if (status == google.maps.GeocoderStatus.OK) {
            if (first_call == 0){
                // Create a Google Map at the latitude/longitude returned by the Geocoder.
                // Create Once
                alert("Initializing Map");
                var myOptions = {
                    zoom: 16,
                    center: results[0].geometry.location,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                //Initialise once
                var map = new google.maps.Map(document.getElementById("map"), myOptions);
            }
            // Add a marker at the address.
            alert("Plotting address");
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
        } else {
                try {
                    console.error("Geocode was not successful for the following reason: " + status);
                } catch(e) {}
            }
    });
    first_call = first_call + 1;
    alert (first_call);
}
</script>
<?php
while($row = mysqli_fetch_array($result)){
    $addr = $row['ADDRESS'];
    echo '<script type="text/javascript">map_function("{$addr}");</script>';
?>

I know that the map along with its options should be initialized only once. So I am keeping a track of the function call using first_call and making sure that the map is initialized only on the first call. Besides, I am declaring the map, options and the geocoder as global variables. Unfortunately, I do not get any output. I am really new to javascript and I dont know where am I going wrong.

Anxiously awaiting a solution.

3
  • Probably many different problems in this code. Here's one. Remove the var in this line var geocoder = new google.maps.Geocoder(); so that you are referencing the global variable, not creating a new temporary local variable. Commented Mar 6, 2014 at 7:50
  • Second problem. Same issue for the map variable. Commented Mar 6, 2014 at 7:50
  • Third problem. You are adding one to first_call at the end of your map_function() function, but that occurs BEFORE the geocode operation completes. You should increment that variable inside the geocode completion callback function. Commented Mar 6, 2014 at 7:52

2 Answers 2

1

I don't know about php code but your javascript code has several errors.

First of all you define mapOptions, map, and geocoder as global and then redefine each of them locally. So, var in front of variables is deleted in function map_function.

The next one which prevents that map is initialized at all is update of first_call variable. Because geocode() is asynchronous function, first_call is set to 1 and then increased further even before code reach the check if (first_call == 0){. So the map is never initialized.

Below is changed code with my test code without php:

<script type="text/javascript">

var myOptions;
var map;
var geocoder;
var first_call = 0;

function map_function(addr){
    // Define the addresses we want to map.
    var clubs = addr;

    // Create a new Geocoder
    if (first_call == 0){
        geocoder = new google.maps.Geocoder(); // var deleted
    }
    // Locate the address using the Geocoder.
    geocoder.geocode( { "address": clubs }, function(results, status) {
        // If the Geocoding was successful
        if (status == google.maps.GeocoderStatus.OK) {
            if (first_call == 0){
                // Create a Google Map at the latitude/longitude returned by the Geocoder.
                // Create Once
                console.log("Initializing Map");
                myOptions = {
                    zoom: 16,
                    center: results[0].geometry.location,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                //Initialise once
                map = new google.maps.Map(document.getElementById("map"), myOptions);
            }
            // Add a marker at the address.
            console.log("Plotting address");
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });

            first_call = first_call + 1;
            console.log (first_call);
        } else {
                try {
                    console.error("Geocode was not successful for the following reason: " + status);
                } catch(e) {}
            }
    });
    // wrong place because of async call: map is never initialized
    //first_call = first_call + 1;
    //console.log (first_call);
}

var addresses = ['Paris', 'London', 'Berlin'];
for (var i = 0; i < addresses.length; i++) {
    map_function(addresses[i]);
}

</script>
Sign up to request clarification or add additional context in comments.

3 Comments

I dont really understand what asynchronous functions are but I will surely read it up. Your code worked. Thanks. :)
Async in this case means that geocoder.geocode() return immediately and doesn't wait that function(results, status) finishes. So first_call is increased before check is done inside function(results, status).
Okay. So thats why the map never initialized. I get it now thanks.
0

Just a bit of output templating mishap. Nothing big. I've rewritten it properly for you.

<?php
while($row = mysqli_fetch_array($result)){
    $addr = $row['ADDRESS'];
    echo '<script type="text/javascript">map_function(' . $addr . ');</script>';
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.