Google maps API function getlatlong - javascript

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);
}

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

getting variables queried from php to javascript

Trying a new method of plotting a marker on google map with my lat/long queried from a data base. when i create variables within the jquery script tag, it works but im not able to make a call outside out that script. But when i try to set those variables with a json_encode from the php array outside of that script, the console returns with
Uncaught SyntaxError: Unexpected token < index:html:29
<!DOCTYPE html>
<html>
<head>
<style>
#map {
width: 1200px;
height: 900px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js">></script>
<script type = "text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(38.4403, -122.5463);
var mapOptions = {
zoom: 10,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title:"Hello World!"
});
marker.setMap(map);
}
var latitude = <?php echo json_encode($lat);?>;
var longitude = <?php echo json_encode($long);?>;
var LatLong = new google.maps.LatLng(latitude, longitude);
var marker1 = new google.maps.Marker({
position: LatLong;
title:"Test"
});
marker1.setMap(map);
</script>
</head>
<body onload = "initialize()">
<div id="map"></div>
</body>
</html>
PHP to query over database:
<?php
require("server_info.php");
$connection=db2_connect($database, $username, $password);
if (!$connection) { die('Not connected : ' . db2_conn_error());}
$query = "SELECT lat,long FROM SCHOOL";
$stmt = db2_prepare($connection, $query);
$result = db2_execute($stmt);
$lat = array();
$long = array();
while ($row = db2_fetch_array($stmt)) {
$lat = $row[0];
$long = $row[1];
}
//echo json_encode($lat);
//echo json_encode($long);
db2_close($connection);
?>
The problem is that your file is named index.html. By default, only files with .php suffix are executed using PHP. Since it has a .html extension, the webserver is just returning the file verbatim to the browser, instead of running it through PHP, so <?php echo json_encode($lat); ?> is sent to the client, and that's not valid Javascript.
You should rename it to index.php, then it will be executed using PHP, and the variables will be substituted.
But it looks like there's more to the problem than this. You never set the variables $lat and $long anywhere in the script. You're setting them in a completely different script.
What you probably should be doing is using AJAX to call the query script from Javascript.

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.

LatLng as an exploded array in Google Maps API

I'm retrieving a string of LatLng coordinates from a database and used PHP's explode function and stored it in an array. I want to pass the array from PHP to JavaScript. Also, I want the Polygon function to accept the array and draw the coordinates accordingly. I'm currently stumped. :( Please help.
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=AIzZfro&sensor=false">
</script>
<script>
function initialize() {
var myLatLng = new google.maps.LatLng(8.5000,125.8333);
var myOptions = {
zoom: 8,
center: myLatLng,
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
myOptions);
var davaoCoordinates = [
new google.maps.LatLng(7.0644,125.6078),
new google.maps.LatLng(8.4833,124.6500),
new google.maps.LatLng(8.5000,125.8333)
];
var davaoCity = new google.maps.Polygon({
path: davaoCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
davaoCity.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Here's the PHP code:
<?php
$connect = mysql_connect("localhost", "root", "");
mysql_select_db('capdb');
if (mysqli_connect_errno()){
echo "Failed to connect to database: " . mysqli_connect_error();
}
$query ="SELECT cap_info.event, cap_info.sendername, cap_info.urgency, cap_area.polygon
FROM cap_info
INNER JOIN cap_area ON cap_info.capid = cap_area.capid
WHERE cap_info.capid =1";
$result = mysql_query($query);
if (!$result){
echo "Query Error." . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0){
echo "No rows found, nothing to print.";
exit;
}
while ($row = mysql_fetch_array($result)){
$event = $row['event'];
$sender = $row['sendername'];
$urgency = $row['urgency'];
$polygon = $row['polygon']."\n";
}
$coordsArray = explode (" ", $polygon);
$count = sizeof($coordsArray);
//$n=0;
//while ($n < $count){
//echo $coordsArray[$n];
//$n++;
//}
?>
Not sure what your array looks like, but, In your php, just create the points for the poly with something like below. That should at least help point you in the right direction.
$poly = "";
// loop all values
foreach($array as $v) {
$poly .= "new google.maps.LatLng(".$v."),\n";
}
// add first item from array to close poly
$poly .= "new google.maps.LatLng(".$array[0].")";
Then, in your javascript, just echo the values where you need them
var map = new google.maps.Map(document.getElementById("map-canvas"),myOptions);
var davaoCoordinates = [
<?php echo $poly; ?>
];

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