fetch data from database and plot it on google map - javascript

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.

Related

Avoid request problems with the Google Maps API(localhost)

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

match zip code or address from php page to google map

I have a PHP page in which address of some person fecth from database table.
Like:
Person name address zip MAP
MR. xyz city1 1234 click
MR. abc city2 1234 click
MR. dfe city3 1244 click
MR. rrr city4 1284 click
If admin clicks on click button of Mr. abc then google map should be open with address or zip of MR. abc and google location should be open on google map of MR. abc
I don't have any idea how to do this? Please give some suggestion.
Now I found a code:
<?php
include("connection.php");
function geocode($address){
// url encode the address
$address = urlencode($address);
// google map geocode api url
$url = "http://maps.google.com/maps/api/geocode/json?address={$address}";
// 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 = $resp['results'][0]['geometry']['location']['lat'];
$longi = $resp['results'][0]['geometry']['location']['lng'];
$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{
return false;
}
}
if($_REQUEST){
// get latitude, longitude and formatted address
$data_arr = geocode($_REQUEST['address']);
// if able to geocode the address
if($data_arr){
$latitude = $data_arr[0];
$longitude = $data_arr[1];
$formatted_address = $data_arr[2];
?>
<!-- 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="http://maps.google.com/maps/api/js"></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
// if unable to geocode the address
}else{
echo "No map found.";
}
}
?>
But it gave an ERROR: **Map shows approximate location.**
Is it right code or not?
You can simply add the address and zip in google map url and open it in new tab. The URL can look like this
http://maps.google.com/maps?q=<address>+<zip>
http://maps.google.com/maps?q=Delhi+110021

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

Google Maps API v3 (PHP & 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.

Categories

Resources