Avoid request problems with the Google Maps API(localhost) - javascript

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

Related

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 function getlatlong

I have this code and problem is that $address_array extract just last position in the array.
How should I fix it?
HMTL
<div id="map"></div>
JQUERY
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
PHP
<?php
function getlatlong($address){
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address) . '&sensor=true';
$json = #file_get_contents($url);
$data = json_decode($json);
if ($data->status == "OK")
return $data;
else
return false;
}
$address_array = array('Germany', 'Poland', 'Italy');
foreach ($address_array as $address) {
$data = getlatlong($address);
$location = $data->results[0]->geometry->location;
}
?>
JS creat map
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: -28.024, lng: 140.887}
});
}
</script>
<script defer src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap"></script>
Fixed
This code wrote one guy and it works great.
The code returns latlng positions.
$address_array = array("Germany", "Poland", "Italy","Italy","Italy");
$encoded_adress_array = [];
foreach ($address_array as $address) {
array_push($encoded_adress_array, getlatlong($address)->results[0]->geometry->location);
}

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 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