multiple google maps markers with PHP - javascript

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));
}
}

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>

Use advanced custom fields value in js for google maps marker

I want to use advanced custom fields to place a Google Map icon. I prefer using the repeater field, but first i'am trying to accomplish a regular field. Image field output is url. I don't understand what i'm doing wrong?
Here is a snippet from my code:
<script>
<?php $image = get_field('marker'); ?>
function initialize() {
//add map, the type of map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: new google.maps.LatLng(52.355692, 5.619524),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//add locations
var locations = [
['Hotspot1', 52.355889, 5.619535,'<?php echo $image ;?>'],
['Hotspot2', 52.354349, 5.618924,'$get_google_map']
];
//declare marker call it 'i'
var marker, i;
//declare infowindow
var infowindow = new google.maps.InfoWindow();
//add marker to each locations
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: locations[i][3]
});
//click function to marker, pops up infowindow
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=hidden&callback=initialize">
</script>
<?php endwhile; ?>
</div>
<?php endif; ?>
Thanks in advance,
Gino
Missing an echo for $get_google_map. Not sure what that represents either since it's not defined
var locations = [
['Hotspot1', 52.355889, 5.619535,'<?php echo $image ;?>'],
['Hotspot2', 52.354349, 5.618924,'$get_google_map']
];
Should be
var locations = [
['Hotspot1', 52.355889, 5.619535,'<?php echo $image ;?>'],
['Hotspot2', 52.354349, 5.618924,'<?php echo $get_google_map ;?>']
];
Inspect the output in browser source to see what the locations array actually looks like or log it to your console with console.log(locations)
Thanks for your quick reply. I changed the code into this:
<script>
<?php $image = get_field('marker'); ?>
function initialize() {
//add map, the type of map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15
, center: new google.maps.LatLng(52.355692, 5.619524)
, mapTypeId: google.maps.MapTypeId.ROADMAP
});
//add locations
var locations = [
['Hotspot1', 52.355889, 5.619535, '<?php echo $image ;?>']
, ['Hotspot2', 52.354349, 5.618924, '<?php echo $image ;?>']
];
Because $get_google_map was from previous testing. But unfortunately the
$image doesn't output anything.

Multiple Marker Strange Click Issue : Google Map API

I'm able to implement multiple markers by using the following code:
<?php foreach($dummy as $cid=>$data)
{ ?>
var myLatlng = new google.maps.LatLng(<?php echo $data['lat']; ?>,<?php echo $data['lon']; ?>);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "<?php echo $data['name']; ?>"
});
icons[j] = marker;
maps[0] = map;
j++;
<?php
}
?>
for(var i = 0; i < icons.length; i++)
{
google.maps.event.addListener(icons[i], 'click', function(){
markerClick(icons[i], maps[0]); // this is the problem area
// markerClick(icons[0], maps[0]); // this works
// markerClick(icons[1], maps[0]); // so does this
});
}
function markerClick(marker_argument, map){
console.log(marker_argument);
}
The issue is with the google.maps.event.addListener function. If I use the variable i, then markerClick()'s console.log() returns undefined. However if I use a hardcoded value (1, 2, or 3), console.log() returns the marker object.
What baffles me is why the argument is not being passed if I use the loop variable i, but works if I hardcode a value. What am I missing here?
Wrap the .addListener loop in a JavaScript closure, and it should work!

Displaying multiple map markers in Google Maps API

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');

how to add google Directions in google maps

The current code retrieves all info, displays all markers on a map and if a marker is clicked, infowindow renders showing its content. What i want to do is that i want to implement directions in this. How can i add directions in my code so that it will also add directions? This is what i want to implement:
what to implement :
var request = {
origin: start,//it will be my first row(lat and lon)
destination: end,//it will be my lastrow(lat and lon)
waypoints: waypts, // it will be all lat and lon between first and last
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status){
if (status == google.maps.DirectionsStatus.OK){
directionsDisplay.setDirections(response);
}
});
My current code in which i want to implement the above functionality mean google maps directions:
already implemented :
$("#directions").click(function(){
var lat_from_ip = $("#hidden_lat").val();
var lon_from_ip = $("#hidden_lon").val();
var latlng = new google.maps.LatLng(lat_from_ip, lon_from_ip);
var options = {zoom: 4, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById('map'), options);
$.ajax({type: "GET",
dataType: 'json',
url: url +'//abc/my_page.php',
success: function(response){
var total=response.length;
var data_array,name,type,address,lat,lon,infowindow;
var infowindow = new google.maps.InfoWindow();
for(var i=0; i < total; i++)
{
data_array=response[i];
name=data_array['name'];
address=data_array['address'];
notes=data_array['notes'];
lat=data_array['lat'];
lon=data_array['lon'];
var propPos = new google.maps.LatLng(lat,lon);
propMarker = new google.maps.Marker({
position: propPos,
map: map,
icon: icon,
zIndex: 3});
var contentString = "<div>"+name+"<br/><label class='label'>Location :</label> "+address+"<br/><label class='label'>Notes :</label> "+notes + "</div>";
function bindInfoWindow(marker, map, infowindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(html);
infowindow.open(map, marker);
});
}
bindInfoWindow(propMarker, map, infowindow, contentString);
} //end of for loop
} //end of for success
}); //end of for $.ajax
return;
});
Function to draw directions, call it whenever you want to show directions. You can pass some variables to it, and use them inside, to decide which markers will be start, end and waypts.
function calcRoute() {
var startpt = yourstartlatlng;
var endpt = yourendlatlng;
var waypts = [] //your waypts array, if there are more than 1 point
var request = {
origin:startpt,
destination:endpt,
waypoints: waypts,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
Example from here: Google Maps Api
EDIT:
When you have an array in php called waypts, and you want to have these values in javascript, you need to pass them to java. Its kinda messy, but thats the only way i know:
<script type="text/javascript">
var waypts = [];
<?php
$waypts= array(1, 2, 3, 4); //<-- your array, can be called like that, or just have values inside already
for($i = 0; $i < sizeof($waypts); $i++){
?>
waypts[<?php echo $i; ?>] = <?php echo $waypts[$i]; ?>; //php is interpreted before java, when site will load, these values will be inside java "waypts" variable.
<?php
}
?>
alert(""+waypts[1]);
</script>
That code will put your php variables/array into java array (alert is just to check if it did the job, you can delete it, once you understand the code). Then you can use these variables however you want. PHP is interpreted earlier than java, so in site code you will get waypts[0] = 1; cuz php code will be already replaced by values from array.
This is how to convert your php array to js array
for instance you have php array
<?php
$my_array = array("a","b","c");
?>
now in js do so
<script>
var jsArray = ["<?php echo join("\", \"", $my_array); ?>"];
alert(jsArray);
and in your domain its like this.
lets say you have php array like this.
$data ;//this is your php array
Array
(
[0] => Array
(
[lat] => 31.453795
[lon] => 74.388497
)
[1] => Array
(
[lat] => 31.454387
[lon] => 74.388541
)
[2] => Array
(
[lat] => 31.453795
[lon] => 74.388497
)
.
.
.
)
in js do so
var waypts = [];
<?php
foreach($data as $key => $value){
if(($key == '0') || ($key == count($data)-1)){
continue;
}?>
waypts.push({location: new google.maps.LatLng(<?php echo $data[$key]['lat'] ?>, <?php echo $data[$key]['lon'] ?>)});
<?php }?>

Categories