Google Maps API v3 (PHP & Javascript) - javascript

I would like to display multiple markers (up to 20 at least) on the Google maps via Javascript. The data which comes in an array is in PHP.
Upon running the code, the Google map only plots the last co-ordinates in the array. Can you guys enlighten me why? Following are the codes (Sorry if this is albeit messy as i'm a novice. thanks for any help in advance):
$link ="http://network-tools.com/default.asp?prog=trace&host="."$ip_address";
$link_traceroute ="http://api.ipinfodb.com/v3/ip-city/?key=a15e8640c34837e4d402df55d7fd5e059e50d0d407d285a7a3b2ccbf85e1a234&ip=";
$response = file_get_contents("$link", false, $context);
$pieces_traceroute = strchr ($response, "$ip_address is from");
$split_pieces_traceroute = str_replace("Trace","$$$",$pieces_traceroute);
$better_pieces_traceroute =(explode("$$$",$split_pieces_traceroute));
$raw_data = strip_tags($better_pieces_traceroute[1]);
$split_data = (explode(" ",$raw_data));
for ($i=0; $i<count($split_data);$i++)
{
$checker= valid_ip($split_data[$i]);
if ($checker != null){
$response_traceroute = file_get_contents("$link_traceroute"."$split_data[$i]", false, $context);
$pieces_traceroute = (explode(";",$response_traceroute));
$Cord1 = $pieces_traceroute[8];
$Cord2 = $pieces_traceroute[9];
echo $Cord1.nl2br("\n");
echo $Cord2.nl2br("\n");
?>
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=true">
</script>
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(<?php echo $Cord1;?>, <?php echo $Cord2;?>);
var myOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title:"Hello World!"
});
// To add the marker to the map, call setMap();
marker.setMap(map);
}

You doesn't need to loop the full js part (including <script> initialize). You get only the last value because of that. Try something like this instead...
// Assume we have $locations variable which hold array data
<script>
function initialize() {
var centerMap = <?php echo json_encode($locations[0]) ?>;
var locations = <?php echo json_encode($locations) ?>;
var centerLatlng = new google.maps.LatLng(centerMap[0], centerMap[1]);
var map = new google.maps.Map(document.getElementById("map_canvas"), {
zoom: 4,
center: centerLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
var marker, i;
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
});
}
}
</script>

Your code is little bit weird. You have count($split_data) times included 'google maps library', closed tag </style>, created map, initialized function initialize. Why? Are you sure that count($split_data)>=20? Have you dumped it? Why don't separate php-part and js-part? You could get all places to be displayed on the map using ajax, or you could even from needed array of obects(each object could contain lat, lng, name, etc) in php. Then make $j_array=json_encode($array) in php-part to convert it to string and var places=<?php echo $j_array; ?>; in js-part to make object again. And than you are to work with array of objects in js. It is much easier and obviously. Refactor your code. It is messed.
I hope it will be helpfull. Sorry for messed english, I treid to be clear.

Related

Inserting markers and info windows (Google Maps) from a database using PHP and javascript

My objective is to obtain data from a table in a database and show it on the map. My table has three columns: LATITUD (stores the latitude)(type=float(10,6)), LONGITUD (stores the longitude)(type=float 10,6) and ASUNTO(stores the information)(type=VARCHAR). The first two have information of the location of the marker, while the third column stores information related to the marker. The content of this last column is the one I want to show with an info window.
To achieve this inside the body element of the page i have decided to insert a script element (javascript) which I use to create the map and to load all the information related to it.
Inside this javascript code I have included PHP code which is in charge of making a query to the database to obtain the content of the table we mentioned at the beggining in an associative array. Inside this code through a while loop I want to load all the markers with their corresponding info windows.
Loading the markers didn't gave me any problem, to load them I used this while loop code.
while ($row = $resultado->fetch( PDO::FETCH_ASSOC )) {
echo ' var myLatlng1 = new google.maps.LatLng('.
$row['LATITUD'].', '.$row['LONGITUD'].');
var marker1 = new google.maps.Marker({
position: myLatlng1,
map: map,
});';
}
Inside the PHP script I inserted this code and works fine to me. I have the problem when I want to add info windows for each marker which contain the information stored in the "ASUNTO" column mentioned at the beggining. When I modify the code shown above to add info windows I have problems. The code that is giving me problems is the one below.
while ($row = $resultado->fetch( PDO::FETCH_ASSOC )) {
echo ' var asunto = '. $row['ASUNTO'] . ';';
echo ' var myLatlng1 = new google.maps.LatLng('.
$row['LATITUD'].', '.$row['LONGITUD'].');
var marker1 = new google.maps.Marker({
position: myLatlng1,
map: map,
});
var infowindow = new google.maps.InfoWindow({
content: asunto
});
infowindow.open(map, marker1);
';
}
I think that the code line that is giving me problems is the first one inside the loop, which I will show now below.
echo ' var asunto = '. $row['ASUNTO'] . ';';
The reason I believe this, is because the "infowindow" variable when I change its content to a string which is not obtained through PHP and is directly inserted doesn't gives me any problem and displays an info window when it is called using the "open"method. The next code below doesn't gives me any problem.
while ($row = $resultado->fetch( PDO::FETCH_ASSOC )) {
echo ' var myLatlng1 = new google.maps.LatLng('.
$row['LATITUD'].', '.$row['LONGITUD'].');
var marker1 = new google.maps.Marker({
position: myLatlng1,
map: map,
});
var infowindow = new google.maps.InfoWindow({
content: "hello"
});
infowindow.open(map, marker1);
';
}
As you can see the content of the infowindow have changed and when I changed it, it worked correctly and the map was able to load. I would like to show info windows which display the information stored in the database rather than the string "hello" of the example above.
I would like to know why my approach is failing and how to resolve the problem in order to be able to show the info windows I want for each marker.
The problem is not with the database, nor the php. The problem is where you echo that data.
One simple example, it's quite obvious that this won't work
while ($row = $resultado->fetch( PDO::FETCH_ASSOC )) {
echo ' var myLatlng1 = new google.maps.LatLng('.
...
The while-loop creates multiple instances of this code. The variable myLatlng1 will simply be overwritten.
What you need to do, is separate the data from the functions.
So you generate 1 var.
It should be something like this (my php is a bit rusty, I hope I'm not generating errors):
<?php
$data = array(); // we make an empty object/array, we will fill it with the data in the rows
while ($row = $resultado->fetch( PDO::FETCH_ASSOC )) {
$data[] = array(
'LATITUD' => $row['LATITUD'],
'LONGITUD' => $row['LONGITUD'],
'ASUNTO' => $row['ASUNTO'],
);
}
// now we echo this variable, 1 variable containing all the data
$data_string = json_encode($data); // this turns php arrays into a javascript-readable object
echo 'var my_data = ' . $data_string .';'; // notice which ; is for javascript and which is for php
?>
var my_data will be something like this (I'll insert some locations in Brussels):
var my_data = [{"LATITUD":"50.89496405015655","LONGITUD":"4.341537103056892","ASUNTO":"Atomium"},{"LATITUD":"50.84501941894387","LONGITUD":"4.349947169423087","ASUNTO":"Manneken Pis"},{"LATITUD":"50.83847065124941","LONGITUD":"4.376028969883903","ASUNTO":"European Parliament"}];
Now the javascript. How do you use infowindows? I'll use my_data hard coded, so you can copy/paste this code and test the javascript.
don't forget your API key
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 90%;
}
</style>
<div id="map"></div>
<script>
var my_data = [{"LATITUD":"50.89496405015655","LONGITUD":"4.341537103056892","ASUNTO":"Atomium"},{"LATITUD":"50.84501941894387","LONGITUD":"4.349947169423087","ASUNTO":"Manneken Pis"},{"LATITUD":"50.83847065124941","LONGITUD":"4.376028969883903","ASUNTO":"European Parliament"}];
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 50.869754630095834, lng: 4.353812903165801},
zoom: 12
});
for(var i=0; i<my_data.length; i++) {
// marker
var position = {lat: Number(my_data[i].LATITUD), lng: Number(my_data[i].LONGITUD)};
var marker = new google.maps.Marker({
position: position,
title: my_data[i].ASUNTO,
map: map
});
// infowindow
var infowindow = new google.maps.InfoWindow({
content: my_data[i].ASUNTO,
map: map,
position: position
});
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>

fetch data from database and plot it on google map

i have an index page that has 2 drop down. second dropdown depends on the first one, after selecting a value from the second list, a search is performed through the database table acc to the value selected and then the matching result is displayed. what i want is that the result that is getting dispalyed(in this case the latitude and longitude corresponding the result) should be shown on google map
code that i have so far
Code on the main page that contains the dropdown and will display the map
<div class="showsearch" id="gmap_canvas"> //place where the ,ap should get displayed
</div>
Code that performs the search to display result and should also work for map
<?php
include("connection.php");
if(isset($_POST['fname']))
{
$fname = mysqli_real_escape_string($con, $_POST['fname']);
$sql1 = 'SELECT * FROM features_for_office WHERE fname LIKE "%'.$fname.'%"';
$result = mysqli_query($con, $sql1);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$latitude= $row["latitude"];
$longitude= $row["longitude"];
}
?>
<!-- JavaScript to show google map -->
<div class="showsearch" id="gmap_canvas"></div>
<script>
function init_map(lat,lang) {
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(lat, lang),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("gmap_canvas"), myOptions);
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>)
});
/*infowindow = new google.maps.InfoWindow({
content: "<?php echo $formatted_address; ?>"
});*/
google.maps.event.addListener(marker, "click", function () {
infowindow.open(map, marker);
});
infowindow.open(map, marker);
}
function loadCoordinates(){
var latitude;
var longitude;
$('.showsearch').blur(function() {
$.ajax({
type: "GET",
dataType: "json",
url: "get_search_data.php",
data: "name="+$(this).val(),
success: function(json){
$('#number').val(json.num);
}
});
});
//call the function once coordinates are available from the server/
//init_map must be called from the call back of ajax function
init_map(latitude,longitude);
}
//instead of init_map call the loadCoordinates to get the values from server
google.maps.event.addDomListener(window, 'load', loadCoordinates);
</script>
<?php }
else
{
echo "0 results";
}
mysqli_close($con);
}
?>
although i am getting the value of latitude and longitude but i am not able to display a map along with markers on specific latitude and longitudes. any help would be appreciated
Considering you are retrieving the coordinate values from server you can modify your map rendering code to load the map based on latitude-longitude values retrieved from server through AJAX. On your page on which you want to show the map you can have below mentioned code.
<div class="showsearch" id="gmap_canvas"> </div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function init_map(lat,lang) {
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(lat, lang),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("gmap_canvas"), myOptions);
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>)
});
/*infowindow = new google.maps.InfoWindow({
content: "<?php echo $formatted_address; ?>"
});*/
google.maps.event.addListener(marker, "click", function () {
infowindow.open(map, marker);
});
infowindow.open(map, marker);
}
function loadCoordinates(){
$('.showsearch').blur(function() {
$.ajax({
type: "GET",
dataType: "json",
url: "get_search_data.php",
data: "name="+$(this).val(),
success: function(json){
var latitude;
var longitude;
latitude = LATITUDE_VALUE_FROM_SERVER;
longitude = LONGTITUDE_VALUE_FROM_SERVER;
init_map(latitude,longitude);
}
});
});
}
//instead of init_map call the loadCoordinates to get the values from server
google.maps.event.addDomListener(window, 'load', loadCoordinates);
</script>
You will require to retrieve the coordinate values from the server using an ajax call and in the call back of ajax function call the function to load the map.

Javascript div breaks my google map

Hi i am using the javascript code below to display google maps inside a show/hide div.
PS I want the map be hidden by default when the page loads. so i wrote this:
<script type="text/javascript">
// <![CDATA[
function showlayer(layer) {
var mymap = document.getElementById(layer).style.display;
if (mymap == "block") {
document.getElementById(layer).style.display = "none";
} else {
document.getElementById(layer).style.display = "block";
}
}
// ]]>
</script>
<div id="mymap" style="display:none;">
<? include $this->loadTemplate( 'map.php' ); ?>
</div>
the map.php file contains the code below:
<script src="http://maps.googleapis.com/maps/api/js?v=3.6&sensor=false" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var mapLatlng = new google.maps.LatLng(<?php echo $this->link->lat . ', ' . $this->link->lng; ?>);
var mapOptions = {
zoom: <?php echo ($this->link->zoom?$this->link->zoom:13); ?>,
center: mapLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marker = new google.maps.Marker({
position: mapLatlng,
map: map,
title:"<?php echo addslashes($this->link->link_name); ?>"
});
}
jQuery(document).ready(function(){initialize();});
</script>
When i remove the style="display:none; everything works ok but i dont want to display the map on page load.
Any help ??
Call initialize after you do document.getElementById(layer).style.display = "block"; because there is a bug I think that does not center the maps correctly in the specified lat and long. So load the map, after the div is shown.

Google Maps API v3 (one infowindow open at a time)

Does someone know how to modify this code so that google maps closes infowindows when you open another?
In other words, I want only one infowindow open at all times. I looked around on stackoverflow but couldn't seem to implement people's solutions in this code.
function initMapsDealers(){
objectLocation = new google.maps.LatLng(25.64152637306577, 1.40625);
var myOptions = {
scrollwheel: false,
zoom: 2,
center: objectLocation,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas-dealers"), myOptions);
var image1 = '/gfx/iconPloegerGreen.png';
var image2 = '/gfx/iconPloegerGreen.png';
var image3 = '/gfx/iconPloegerDealer.png';
/* Info windows */
<?
function replace_newline($string) {
return (string)str_replace(array("\r", "\r\n", "\n"), '', $string);
}
$i = 0;
foreach($dealers as $dealer)
{
$dealerLanden[$dealer['Land']][] = $dealer;
if($dealer['lat'] != "" && $dealer['lon'] != "")
{
$i++;
?>
objectLocation<?= $i; ?> = new google.maps.LatLng(<?= $dealer['lat']; ?>, <?= $dealer['lon']; ?>);
var contentString<?= $i; ?> =
'<div class="infoWindow">'+
'<strong><?= str_replace("'","", $dealer['name']); ?></strong><br>'+
'<?= replace_newline($dealer['content']); ?>'+
'</div>';
var infowindow<?= $i; ?> = new google.maps.InfoWindow({
content: contentString<?= $i; ?>
});
var marker<?= $i; ?> = new google.maps.Marker({
position: objectLocation<?= $i; ?>,
title:"<?= $dealer['name']; ?>",
map: map,
icon: <?
if($dealer['group'] == "Hoofdkantoor"){ ?>image1<? }
elseif($dealer['group'] == "Oxbo"){ ?>image2<? }
elseif($dealer['group'] == "Dealers"){ ?>image3<? }
else{ ?>image1<? }?>
});
google.maps.event.addListener(marker<?= $i; ?>, 'click', function() {
infowindow<?= $i; ?>.open(map,marker<?= $i; ?>);
});
<?
}
}
?>
resizeSection();
};
There is a google recommendation what to do if you only want one InfoWindow API documentaion for InfoWindow.
It is:
InfoWindows may be attached to either Marker objects (in which case
their position is based on the marker's location) or on the map itself
at a specified LatLng. If you only want one info window to display at
a time (as is the behavior on Google Maps), you need only create one
info window, which you can reassign to different locations or markers
upon map events (such as user clicks). Unlike behavior in V2 of the
Google Maps API, however, a map may now display multiple InfoWindow
objects if you so choose.
To change the info window's location you may either change its
position explicitly by calling setPosition() on the info window, or by
attaching it to a new marker using the InfoWindow.open() method. Note
that if you call open() without passing a marker, the InfoWindow will
use the position specified upon construction through the InfoWindow
options object.
So try to follow these suggenstions.
This is my solution to have only one infowindow open at one time:
infowindow = new google.maps.InfoWindow({
content: infocontent,
maxWidth: 200
});
google.maps.event.addListener(marker, 'click', function() {
if($('.gm-style-iw').length) {
$('.gm-style-iw').parent().hide();
}
infowindow.open(map,marker);
});

Fetch data from database and use it to make markers in Google Maps

I am new to Javascript. I want to fetch lat-long from MySQL (more then 100) and use it to add markers on Google Maps.
To do this I think i've to use php -server side programming. I am able to pass array from PHP to Javascript. Here it is
<?
mysql_connect('localhost', 'username', 'pwd') or die(mysql_error());
echo "Connected to MySQL<br />";
mysql_select_db("pro_user") or die(mysql_error());
$result = mysql_query("SELECT * FROM info");
$no=count($result);
$i=0;
while($row = mysql_fetch_array( $result ))
{
$a[$i]=$row['city'];
$b[$i]=$row['loc_lat'];
$c[$i]=$row['loc_long'];
$i++;
}
?>
<html>
<head>
<script type="text/javascript">
function initialize()
{
var latlng = new google.maps.LatLng(22.3038945, 70.8021599);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<? for($i=0;$i<count($a); $i++)
{
echo "a[$i]='".$a[$i]."';\n";
echo "b[$i]='".$b[$i]."';\n";
echo "c[$i]='".$c[$i]."';\n";
}
?>
function createMarker(latitude,longitude,title)
{
var markerLatLng = new google.maps.LatLng(latitude,longitude);
var marker = new google.maps.Marker({ position: markerLatLng, map: map, title: title });
}
createMarker(22.3038945, 70.8021599,'Gujarat');
for(i=0;i<a.length;i++)
{
document.write(a[i]);
document.write(b[i]);
document.write(c[i]);
initialize().createMarker(b[i], c[i], a[i]);
}
}
</script>
</head>
<body onload="getData()"></body>
</html>
Now I am stuck. I am not able to pass Javascript array to make markers.
There is a very simple tutorial on the google maps website for doing this using PHP / XML / MySQL and Javascript ....
http://code.google.com/apis/maps/articles/phpsqlajax.html

Categories

Resources