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.
varin this linevar geocoder = new google.maps.Geocoder();so that you are referencing the global variable, not creating a new temporary local variable.mapvariable.first_callat the end of yourmap_function()function, but that occurs BEFORE the geocode operation completes. You should increment that variable inside the geocode completion callback function.