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.
Related
I have a problem trying to use Google Maps API in my code.
The problem is that with my code and my API KEY without restrictions, I get an ERROR: OVER_QUERY_LIMIT error.Althought if I put restrictions to my API KEY(localhost,https://localhost,https://localhost:80....)I have an ERROR: REQUEST_DENIED.
function geocode($address){
// url encode the address
$address = urlencode($address);
// google map geocode api url
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=
{$address}&key=AIzaSyDZaPEOrHX1Xd0VfiX2aV2xfn7_XeHiSls";
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
// response status will be 'OK', if able to geocode given address
if($resp['status']=='OK'){
// get the important data
$lati = isset($resp['results'][0]['geometry']['location']['lat']) ?
$resp['results'][0]['geometry']['location']['lat'] : "";
$longi = isset($resp['results'][0]['geometry']['location']['lng']) ?
$resp['results'][0]['geometry']['location']['lng'] : "";
$formatted_address = isset($resp['results'][0]['formatted_address'])
? $resp['results'][0]['formatted_address'] : "";
// verify if data is complete
if($lati && $longi && $formatted_address){
// put the data in the array
$data_arr = array();
array_push(
$data_arr,
$lati,
$longi,
$formatted_address
);
return $data_arr;
}else{
return false;
}
}
else{
echo "<strong>ERROR: {$resp['status']}</strong>";
return false;
}
}
?>
<!-- google map will be shown here -->
<div id="gmap_canvas">Loading map...</div>
<div id='map-label'>Map shows approximate location.</div>
<!-- JavaScript to show google map -->
<script type="text/javascript" src="https://maps.google.com/maps/api/js?
key=AIzaSyDZaPEOrHX1Xd0VfiX2aV2xfn7_XeHiSls"></script>
<script type="text/javascript">
function init_map() {
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(<?php echo $latitude; ?>, <?
php echo $longitude; ?>),
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);
}
google.maps.event.addDomListener(window, 'load', init_map);
</script>
<?php
I would like to know how I could load the coordinates (longitude and latitude) of my database in real time without updating the page even if there will be changes in the database.
I used setInterval (function ()) to reload data but still get the same coordinates.
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=fma120;charset=utf8', 'root', '');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$reponse = $bdd->query('SELECT latitude,longitude FROM gps_data ORDER BY id DESC LIMIT 1 ');
$donnees = $reponse->fetch() ;
?>
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<script>
function initMap() {
var uluru = {lat:<?php echo $donnees['latitude'] ;?> , lng: <?php echo $donnees['longitude'] ;?>
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
setInterval(function(){ initMap() }, 3000);
</script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyADJopukImlmQs73l4o3xdddlcg_OBj1vaqB8&callback=initMap">
</script>
</body>
</html>
I explain:
my script loads the map (the last id = 1) .. after I add another column in the database (with id = 2), I would like the script to load the last column (id = 2) without updating the page
Please help me
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);
});
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
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.