Displaying multiple map markers in Google Maps API - javascript

working on some perl code in a .cgi file that loops through a hash list of IP addresses, then runs each IP address through a web service that returns that latitude and longitude of the IP address, then it needs to display each IP address as a marker on a google map. As of right now I have it running through the hashlist and printing the coordinates of each IP address. What I can't figure out is how to display more than one map marker on the google map. I am currently just testing it by hardcoding values to the $latitude and $longitude variables. I am thinking that there needs to be some sort of loop in the javascript that will run through and assignin each coordinate, but I have no idea on how to approach that.
Update: I have added the code from the first answer and have the list successfully printing outside of the loop. The problem I am having now is that the google map will no longer load. I have narrowed the problem down to the javascript where the latitudes and longitudes variable assigned its value.
unless ($result->fault) {
# Print out the results one by one
my $latitude = "LATITUDE = " . $result->valueof('//LATITUDE') . "\n";
my $longitude = "LONGITUDE = " . $result->valueof('//LONGITUDE') . "\n";
#print "MESSAGE = " . $result->valueof('//MESSAGE') . "\n";
$lats .= $latitude . ',';
$lons .= $longitude . ',';
} else {
print "IP2Location Web Service Failed!\n";
print join ', ',
$result->faultcode,
$result->faultstring,
$result->faultdetail;
}
}
chop $lats;
chop $lons;
#printing here to test if the variable is making it out of the loop
print $lats ;
print $lons ;
print <<ENDHTML;
<html>
<head>
<title>IP Lookup Map</title>
<meta name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<style type="text/css">
html, body, #map_canvas {
margin: 0;
padding: 0;
height: 90%;
width: 90%;
}
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//If I comment out the following variables the map will load, not sure what the problem is
var latitudes = "$lats".split(",");
var longitudes = "$lons".split(",");
var map;
function initialize() {
var myOptions = {
zoom: 7,
center: new google.maps.LatLng(44, -90),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
// Creating a marker and positioning it on the map
for(var i = 0; i < latitudes.length; i++){
var latitude = latitudes[i];
var longitude = longitudes[i];
// Creating a marker and positioning it on the map
var marker = new google.maps.Marker({
position: new google.maps.LatLng(latitude,longitude),
map: map
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

Obviously you need to save all the latitudes and longitudes, rather than just print them. I'd use 2 globals, outside your unless($result){
my $lats = '';
my $lons = '';
....
$lats .= $latitude . ',';
$lons .= $longitude . ',';
(You might need a chop($lats); chop($lons) after the loop to remove the last comma) Then in your javascript section:
// create two arrays from that lats and lons string using split()
var latitudes = "$lats".split(',');
var longitudes = "$lons".split(',');
.....
// create map code
....
for(var i = 0; i < latitudes.lenght; i++){
var latitude = latitudes[i];
var longitude = longitudes[i];
// Creating a marker and positioning it on the map
var marker = new google.maps.Marker({
position: new google.maps.LatLng(latitude,longitude),
map: map
});
}

Fixed it and have everything working now. The problem was that the $latitude and $longitude variables where still being assigned a bunch of extra text that was not needed. Now it is just assigned the value.
my $latitude = $result->valueof('//LATITUDE');
my $longitude = $result->valueof('//LONGITUDE');

Related

how to indicate multiple custom marker on map using fetch lat and long data from mysql db

i have try to fetch lat and long value from mysql db and pass those value on google map for show location marker on map
but currently i have fetch only last rows data so indicate marker only one place
how to display all location on map??
<?php
include "config.php";
$result="select * from ds_duty_history";
$a=mysqli_query($conn,$result);
// $count_row = mysqli_num_rows($a);
while ($b = mysqli_fetch_array($a)) {
$long_d=$b['lng'];
$lat_d=$b['lat'];
$result = array(array('latitude'=>$lat_d,'longitude'=>$long_d));
}
?>
<!doctype html>
<html>
<head>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOURKEY&callback=initMap">
</script>
<script type="text/javascript">
var map;
function initialize() {
// Set static latitude, longitude value
var latlng = new google.maps.LatLng(<?php echo $lat_d; ?>, <?php echo $long_d; ?>);
// Set map options
var myOptions = {
zoom: 16,
center: latlng,
panControl: true,
zoomControl: true,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// Create map object with options
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?php
// uncomment the 2 lines below to get real data from the db
// $result = mysql_query("SELECT * FROM parkings");
// while ($row = mysql_fetch_array($result))
foreach($result as $row){ // <- remove this line
echo "addMarker(new google.maps.LatLng(".$row['latitude'].", ".$row['longitude']."), map);";}
?>
}
function addMarker(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map,
draggable: true, // enables drag & drop
animation: google.maps.Animation.DROP
});
return marker;
}
</script>
</head>
<body onload="initialize()">
<div style="float:left; position:relative; width:550px; border:0px #000 solid;">
<div id="map_canvas" style="width:550px;height:400px;border:solid black 1px;"></div>
</div>
</body>
</html>
currently display only one marker i.e last fetch record lat and long assign on map
how to display all place on map using mysql lat,long value?
The main problem you have here is that you're not actually collecting different results in your $result variable but overwrite it with the most recent one. The also seems to be some abuse of the variable $result which might be contributing to your confusion. Let's say we declare a new array and call it $rows. Then we can collect all the rows with the following code (to substitute your first snippet):
<?php
include "config.php";
$sql = "SELECT * FROM ds_duty_history";
$result = mysqli_query($conn, $sql);
$rows = [];
while ($row = mysqli_fetch_array($result)) {
$lon_d = $row['lng'];
$lat_d = $row['lat'];
// Use short-cut append syntax here so we add row and don't overwrite $rows
$rows[] = ['latitude' => $lat_d, 'longitude' => $long_d];
}
?>
Now in your display code (the second snippet) you would be able to iterate over $rows pretty much like:
foreach ($rows as $row){
// Do work with each $row here
}
Just as an aside, try to get used to using variable names that are as meaningful as possible and use new variables as much as you can. Trying to use short, generic variable names like $a will always lead to confusion since you won't know what it represents unless you find where you declared it every time. Trying to re-use a variable (like you did with $result) can make your life much more difficult since now even if you find an assignment to the variable, it is assigned many different times and (the way you used it) represents completely different types each time. Doing this one thing makes it just a little easier to get the hang of programming since at the very least you'll be able to read and make sense of your own intent when reading your own code.
Please try this code for display multiple marker on map
<script type="text/javascript">
var LocationData = <?php echo json_encode($result); ?>;
function initialize()
{
var myOptions = {zoom:12,mapTypeId: google.maps.MapTypeId.ROAD};
var map =
new google.maps.Map(document.getElementById('map-canvas'), myOptions);
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
for (var i in LocationData)
{
var p = LocationData[i];
var latlng = new google.maps.LatLng(p[0], p[1]);
bounds.extend(latlng);
var icon = { url: '<?php echo base_url();?>assets/frontend/assets/images/location_pin1.png', // url
scaledSize: new google.maps.Size(40, 70), // scaled size
origin: new google.maps.Point(0,0), // origin
anchor: new google.maps.Point(0, 0) // anchor
};
var marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: true, // enables drag & drop
animation: google.maps.Animation.DROP
icon: icon
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

Google Maps how to change the Marker Icon to an Icon that is referenced in a directory from an SQL Database?

Hi all I was wondering if anyone could help me with my code I want to change the Marker Icon to an Icon that is referenced in a directory from an SQL Database. Here is a link to a screen capture of the database.
http://i.stack.imgur.com/SriRX.png
This Database works great with the PHP on my website all except for the icons. As shown in the screen capture at this link. http://i.stack.imgur.com/ccGP1.png
It seems as if the last icon referenced in the database is the icon that is used for all markers but I do not want this to happen instead I want individual markers all looking different. The information contained in the markers is also correct. At the bottom of the inside of the content box it shows the icon directory which is correct on all but I have no idea why I can't get the actual icon to change to the directory shown in the content box. Below is an example of the PHP code used:
<html>
<head>
<script type='text/javascript' src='js/jquery-1.6.2.min.js'></script>
<script type='text/javascript' src='js/jquery-ui-1.8.14.custom.min.js'></script>
<style>
BODY {font-family : Verdana,Arial,Helvetica,sans-serif; color: #000000; font-size : 13px ; }
#map_canvas { width:100%; height: 100%; z-index: 0; }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false" /></script>
<script type='text/javascript'>
//This javascript will load when the page loads.
jQuery(document).ready( function($){
//Initialize the Google Maps
var geocoder;
var map;
var markersArray = [];
var infos = [];
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
//Load the Map into the map_canvas div
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//Initialize a variable that the auto-size the map to whatever you are plotting
var bounds = new google.maps.LatLngBounds();
//Initialize the encoded string
var encodedString;
//Initialize the array that will hold the contents of the split string
var stringArray = [];
//Get the value of the encoded string from the hidden input
encodedString = document.getElementById("encodedString").value;
//Split the encoded string into an array the separates each location
stringArray = encodedString.split("****");
var x;
for (x = 0; x < stringArray.length; x = x + 1)
{
var addressDetails = [];
var marker;
//Separate each field
addressDetails = stringArray[x].split("&&&");
//Load the lat, long data
var lat = new google.maps.LatLng(addressDetails[1], addressDetails[2]);
//Create a new marker and info window
marker = new google.maps.Marker({
map: map,
position: lat,
icon: icon,
//Content is what will show up in the info window
content: addressDetails[0]
});
//Pushing the markers into an array so that it's easier to manage them
markersArray.push(marker);
google.maps.event.addListener( marker, 'click', function () {
closeInfos();
var info = new google.maps.InfoWindow({content: this.content});
//On click the map will load the info window
info.open(map,this);
infos[0]=info;
});
//Extends the boundaries of the map to include this new location
bounds.extend(lat);
}
//Takes all the lat, longs in the bounds variable and autosizes the map
map.fitBounds(bounds);
//Manages the info windows
function closeInfos(){
if(infos.length > 0){
infos[0].set("marker",null);
infos[0].close();
infos.length = 0;
}
}
});
</script>
</head>
<body>
<div id='input'>
<?php
//Connect to the MySQL database that is holding your data, replace the x's with your data
mysql_connect("localhost", "xxxx_xxxx", "xxxx") or
die("Could not connect: " . mysql_error());
mysql_select_db("xxxx_map");
//Initialize your first couple variables
$encodedString = ""; //This is the string that will hold all your location data
$x = 0; //This is a trigger to keep the string tidy
//Now we do a simple query to the database
$result = mysql_query("SELECT * FROM `markers`");
//Multiple rows are returned
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
//This is to keep an empty first or last line from forming, when the string is split
if ( $x == 0 )
{
$separator = "";
}
else
{
//Each row in the database is separated in the string by four *'s
$separator = "****";
}
//Saving to the String, each variable is separated by three &'s
$image = $row[4];
$icon = $row[5];
$description = $row[6];
$encodedString = $encodedString.$separator.
"<p class='content' align='center'><b><img src='".$image."' width='147' height='150'><br/><br>".$description."<br>".$icon."</b> ".
"</p>&&&".$row[1]."&&&".$row[2];
$x = $x + 1;
}
?>
<script>
icon = '<?php echo $icon ?>';
</script>
<input type="hidden" id="encodedString" name="encodedString" value="<?php echo $encodedString; ?>" />
<hr>
<input type="text" id="icon" name="icon" value="<?php echo $icon; ?>" />
</div>
<div id="map_canvas"></div>
</body>
</html>
You are setting icon value to the last retrieved from the database in this piece of code
<script>
icon = '<?php echo $icon ?>';
</script>
You should, instead, get it from the addressDetails string as you have done for latitude, longitude and content.

Continuously updating Google Maps with user location

I am super new to web development and building a web app that has a google map and would like to continuously update the map with the user location. I am able to read values from my db properly and can display it on the map, but only one time. I could not find anywhere how to continuously update the position (hopefully without reloading the page also). Can someone help with some direction on how to approach this? Here some of my code for reference:
<?php include_once('location.php') ?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>My GeoLocation</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(<?php echo $current_lat ?>, <?php echo $current_long ?>);
var mapOptions = {
zoom: 14,
center: myLatlng
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'TEST'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
//READ FROM CLIENT (POST)
$content = file_get_contents('php://input');
$post_data = json_decode($content , true);
$lat = $post_data['lat'];
$long = $post_data['long'];
$speed = $post_data['speed'];
$hacc = $post_data['hacc'];
$vacc = $post_data['vacc'];
$timestamp = $post_data['timestampe'];
//CONNECT TO MYSQL
$con1 = mysql_connect("localhost", "xxxxxxxx", "bbbbbb", "yyyyyy");
if ($con1->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$db_selected = mysql_select_db('yyyyyy');
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
if (!empty($lat)) {
$sql = "INSERT INTO LocationInfo (latitude, longitude, speed, hor_acc, ver_acc, d)
VALUES ('$lat', '$long', '$speed', '$hacc', '$vacc', '$timestamp');";
mysql_query($sql) or die ('Error updating database: ' . mysql_error());
}
$read_query = "SELECT * FROM LocationInfo;";
$results = mysql_query($read_query) or die ('Error reading from database: ' . mysql_error());
$column = array();
while($row = mysql_fetch_array($results)){
$column[] = $row;
}
$current_lat = $column[sizeof($column) - 1]['latitude'];
$current_long = $column[sizeof($column) - 1]['longitude'];
?>
Google Maps JavaScript reference
You can update the marker with marker.setPosition( new LatLng(...) ), or in other words just assigning a new position. It seems to me you're putting your position in an input field, than submitting, reading the field and setting the marker and saving the position in a database. If you want to update the position of the marker, you can use an input field again, read the field value with JavaScript, and update the marker's position (with marker.setPosition()). If you want to pass this to your DB again, you can additionally pass the data to your script using AJAX. It depends on what you're doing and want you want to do.
edited after comment
You can setup a JavaScript function that will make an AJAX request to your PHP script and update the position once it gets the data. And then call the script every x number of seconds. use setTimeout to create a delay and then make the function call itself with another timeout once it gets the data. Save yourself the trouble and use a library to handle your AJAX calls - jQuery gives you indirectly a lot of support because a lot of people use it. You also need to make sure your PHP script doesn't give you anything back except the position information, not the whole html file as you have now. So simplified something like this: you have a PHP file that sends you the lat/lng pair as JSON, and this script gets called from the browser around every 10 seconds. There are ofcourse little things that might pop out ... and please note, I don't do PHP.
get_position.php
...
$latLng = array('lat' => $lat, 'lng' => $lng);
echo json_encode($latLng);
JS, using jQuery.ajax
var marker = ....
var delay = 10000; // 10 second delay
function updatePosition() {
$.ajax({
url: path/to/get_position.php,
dataType: 'json'
})
.done(function callDone(data) {
// update marker position
var latLng = new google.maps.LatLng( data.lat, data.lng );
marker.setPosition( latLng );
// call the function again
setTimeout( updatePosition, delay );
});
}
// call the function initally
setTimeout( updatePosition, delay );

Retrieving values from a php service in HTML

I am trying to build a website that displays a google map with a user location (lat/long) from a php service that I wrote.
I already have a php script that gets the lat/long from a mobile app (via POST from the client), stores it in a DB, and read it back from the DB into two variables, let's call them $lat and $long. To make sure I have the right values in $lat and $long, I did a simple echo and got the two values.
I am struggling with understanding how to read these values from my index.html script. All the examples that I have seen suggest keeping the php code in the html file but I would rather keep them separate. I am also not sure how to assign these values to parameters in HTML/Javacript so I can actually display them on the map.
So my questions are: 1. how do I call that php file from HTML? 2. and how do I read $lat and $long from the php service and assign them to parameters in HTML/Javascript that I can display on the map?
EDIT: here is my PHP code and my index.html (Which is a 1:1 copy from the Google Maps v3 docs).
location.php:
$content = file_get_contents('php://input');
$post_data = json_decode($content , true);
$lat = $post_data['lat'];
$long = $post_data['long'];
//CONNECT TO MYSQL
$con1 = mysql_connect("localhost", "xxxxx", "yyyy", "zzzzz");
if ($con1->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
if (!empty($lat)) {
$sql = "INSERT INTO LocationInfo (latitude, longitude)
VALUES ('$lat', '$long');";
mysql_query($sql) or die ('Error updating database: ' . mysql_error());
}
$read_query = "SELECT * FROM LocationInfo;";
$results = mysql_query($read_query) or die ('Error reading from database: ' . mysql_error());
$column = array();
while($row = mysql_fetch_array($results)){
$column[] = $row;
}
$current_lat = $column[sizeof($column) - 1]['latitude'];
$current_long = $column[sizeof($column) - 1]['longitude'];
echo $current_lat;
echo $current_long;
?>
index.html:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>My GeoLocation</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 14
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
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: 'Location found using HTML5.'
});
The easiest way to get those variables in Javascript is to output them from PHP to JS, there is no direct bridge, so you will need in the HTML output a script block with the values you got from your SQL query, it will be something like this:
<script>
var lat = <?php echo $lat ?>;
var long = <?php echo $long ?>;
</script>
Now you can use this variables in your javascripts to invoke the map, as a note you can add the variables definition to your main JS block as well.
EDIT:
Rename index.html to index.php
<?php include_once('location.php') ?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>My GeoLocation</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
var map;
function initialize() {
// var myLatlng = new google.maps.LatLng(<?php echo $lat ?>,<?php echo $long ?>);
var mapOptions = {
zoom: 14
//mapTypeId: google.maps.MapTypeId.ROADMAP
//center: myLatlng
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
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: 'Location found using HTML5.'
});

multiple google maps markers with PHP

I've had a look around SO and found some situations similar to mine but haven't found a solution.
I'm learning PHP, Javascript as I go along so the code may be a little off but here goes:
I have a Google map with a postcode search function working - The postcode and Lat/Long are stored in a Mysql DB. What I need now is a function to place any amount of markers on the map for specific postcodes - in time I hope to expand the function to allow something like postcode+10 miles, etc depending on the zoom level. The code below will bring back the lat/long for the markers but it sticks a "," at the end of each results and therefore when I pass it into the javascript, it's an invalid parameter - please be sure that I know that the way I'm doing all of this is in-efficient - I'm learning as I go along :)
PHP function:
// get markers Function
if(!function_exists("getMarkers"))
{
//Get Markers Function
function getMarkers()
{
//prep the query
include ('../../secure/db_conn.php');
$currentPcode = searchPostcode($_POST['postcode']);
$tsearch = $con->prepare("SELECT t.CompanyName, p.lat, p.lng FROM Traders t, cpo_data p WHERE t.Postcode LIKE p.Postcode");
$tsearch->bindParam(1,$currentPcode, PDO::PARAM_STR);
$tsearch->execute();
$tresults = $tsearch->fetchAll(PDO::FETCH_ASSOC);
foreach ($tresults as $row)
{
$Company = $row['CompanyName'];
$Tlat = (string)$row['p.lat'];
$Tlng = (string)$row['p.lng'];
}
echo $Tlat .", " .$Tlng;
}
}
Javascript:
<script src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script>
//postcode function call
var myCenter=new google.maps.LatLng(<?php echo searchPostcode($_POST['postcode']); ?>);
//markers function call
var locations=new google.maps.LatLng(<?php echo getMarkers(); ?>);
function initialize()
{
var mapProp = {
center:myCenter,
zoom:14,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var mymap=new google.maps.Map(document.getElementById("googleMap"),mapProp);
// To add the marker to the map, use the 'map' property
var marker, i;
for (i = 0; i < locations.length; i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i]),
map: mymap
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i]);
infowindow.open(mymap, marker);
}
})(marker, i));
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Any help or advice will be greatly appreciated - my current knowledge is only PHP and Javascript (and as mentioned previously, it's beginners knowledge).
Forgot to add, When I use google developer tools in Chrome to analyse the page, I can see the following which confirms it is picking up the lat/long, but with a comma at the end (I think it's to do with it being an array but not sure how I deal with it):
var locations=new google.maps.LatLng(53.51139969260000, -2.54091408438000, );
If you want to place the markers fetched from the database you have two problems:
PHP Code
You echo only the last pair of lat/lng fetched:
foreach ($tresults as $row)
{
$Company = $row['CompanyName'];
$Tlat = (string)$row['p.lat'];
$Tlng = (string)$row['p.lng'];
}
echo $Tlat .", " .$Tlng;
A solution would be:
$locations = array();
foreach ($tresults as $row)
{
$Company = $row['CompanyName'];
$Tlat = (string)$row['p.lat'];
$Tlng = (string)$row['p.lng'];
$locations[] = "[" . $Tlat .", " .$Tlng . "]";
}
echo srpintf("[%s]", implode(", ", $locations);
Then in your javascript code you store an array of coordinates in locations.
Javascript code
Now in your javascript code:
var locations = <?php getMarkers(); ?>
You have now in locations the array like this:
[[53.51139969260000, -2.54091408438000], [...], ...]
Then in the loop you should access to coordinates as an array:
var marker, i;
for (i = 0; i < locations.length; i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
map: mymap
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0] + ", " + locations[i][1]);
infowindow.open(mymap, marker);
}
})(marker, i));
}
}

Categories