match zip code or address from php page to google map - javascript

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

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

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.

Google map custom marker based on database

In 2 weeks I explored much about Google maps. I am try read a forum and tutorial. But I got this problem when I am going to develop a GIS web. I am using Google maps apiv3, postgre database, and php. I have so much row in my database. Now I only can show multiple marker based on my database, but what I after is the marker have a unique icon based on column content in database like a type 1 = 1.png type 2 = 2.png. the problem is the type is too many, so it is impossible to definition them by manual (because so many type, I already have about 30 type of content in database column ) . I get database value using json. I've already try read forum and some tutorial, but I can't find the answer. sorry for my bad english. please help me, thanks.
this is the code index.php and json.php :
<html lang="en">
<head>
<script type="text/javascript">
function initialize(){
var peta;
var gambar_tanda;
gambar_tanda = 'assets/images/enseval.jpg';
var x = new Array();
var y = new Array();
var customer_name = new Array();
var rayon_name = new Array();
// posisi default peta saat diload
var lokasibaru = new google.maps.LatLng( -1.2653859,116.83119999999997);
var petaoption = {
zoom: 5,
center: lokasibaru,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
peta = new google.maps.Map(document.getElementById("map_canvas"),petaoption);
var infowindow = new google.maps.InfoWindow({
content: ''
});
// memanggil function ambilpeta() untuk menampilkan koordinat
url = "json.php";
$.ajax({
url: url,
dataType: 'json',
cache: false,
success: function(msg){
for(i=0;i<msg.enseval.customer.length;i++){
x[i] = msg.enseval.customer[i].x;
y[i] = msg.enseval.customer[i].y;
customer_name[i] = msg.enseval.customer[i].nama_customer;
//rayon_name[i] = msg.enseval.customer[i].nama_rayon
var point = new google.maps.LatLng(parseFloat(msg.enseval.customer[i].x),parseFloat(msg.enseval.customer[i].y));
tanda = new google.maps.Marker({
position: point,
map: peta,
icon: gambar_tanda,
clickable: true
});
bindInfoWindow(tanda, peta, infowindow, msg.enseval.customer[i].nama_customer );
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function bindInfoWindow(tanda, peta, infowindow, data) {
google.maps.event.addListener(tanda, 'click', function() {
infowindow.setContent(data);
infowindow.open(peta, tanda);
});
}
</script>
<?php
require ('config.php');
$rayon = $_POST['rayon'];
$cabang = $_POST['org_id'];
//echo "$rayon, $cabang, $rayonhasil";
$sql = "SELECT distinct org_id, customer_name, attribute16, attribute17 FROM hasilgis";
$data = pg_query($sql);
$json = '{"enseval": {';
$json .= '"customer":[ ';
while($x = pg_fetch_array($data)){
$json .= '{';
$json .= '"id_customer":"'.$x['org_id'].'",
"nama_customer":"'.htmlspecialchars($x['customer_name']).'",
"x":"'.$x['attribute17'].'",
"y":"'.$x['attribute16'].'"
},';
}
$json = substr($json,0,strlen($json)-1);
$json .= ']';
$json .= '}}';
echo $json;
?>
I'm not sure what's the problem :)
The only thing you must do is to generate icons for all types. You don't have to do it manually - just create a scipt that will generate icons of different colors for every type and name it like 1.jpg, 2.jpg, ...
Pass type via your json message and than on client side create icon url dynamically:
gambar_tanda = 'assets/images/'+msg.enseval.customer[i].type+'.jpg';

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