Google Maps - Getting points in Php array, to points on a map - php

So i have a page called region.php, which in the header, loads JQuery, the google maps API, and the custom Jquery functions I use for my app in a file called functions.js.
In region.php, I pull a few rows from the MySQL DB and store them in a php array, $regions.
In my functions.js file, I'm trying to json_encode the $regions array, and pass it to my function, to plays all of the lats and longitudes of the $regions array on the google map. However, IM having trouble getting the Php array into Javascript.
I had been following this but it doesnt seem to be working for me: Iterating through a PHP array in jQuery?. Doesn't seem like the javascript can work with the php in the example they give
any ideas? (and I suppose if im going about this all wrong -- what is the best way to get the php array into javascript?
Region.php
$regions = get_regions();
foreach($regions as $region) :
print $region['name'];
endforeach;
print "<div id='map_view_canvas' style=\"width:300px; height:300px; \"></div>";
functions.js
$(document).ready(function() {
initialize_view_map();
}
function initialize_view_map()
{
var latlng = new google.maps.LatLng(9.3939, 20.57268);
var myOptions = {
zoom: 2,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_view_canvas"), myOptions);
var mapPoints = <?php echo json_encode($regions) ?>;
$.each(mapPoints, function (i, elem) {
var newLatLng = new google.maps.LatLng(elem.latitude, elem.longitude);
var marker = new google.maps.Marker({
position: newLatLng,
map: map,
draggable:false,
animation: google.maps.Animation.DROP
});
});
}

From the example you link to:
var arrayFromPHP = <?php echo json_encode($viewFields) ?>;
that needs to go in a php file not your functions.js file, which is what it sounds like you've done. The code between is php, so needs to run on the server side, it can't run in javascript (which is client side and so knows nothing about php or any server side code\variables\etc)
EDIT:
Now that you've added your code, try something like the following. Sorry, I'm not too familar with php, but hopefully you get the idea:
Regions.php
$regions = get_regions();
foreach($regions as $region) :
print $region['name'];
endforeach;
print "<script>";
print "var mapPoints = ";
echo json_encode($regions->toArray());
print "</script>";
print "<div id='map_view_canvas' style=\"width:300px; height:300px; \"></div>";
Then your Javascript becomes (note the mapsPoint variable has been output by the regions.php already so I remove it here)
$(document).ready(function() {
initialize_view_map();
}
function initialize_view_map()
{
var latlng = new google.maps.LatLng(9.3939, 20.57268);
var myOptions = {
zoom: 2,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_view_canvas"), myOptions);
$.each(mapPoints, function (i, elem) {
var newLatLng = new google.maps.LatLng(elem.latitude, elem.longitude);
var marker = new google.maps.Marker({
position: newLatLng,
map: map,
draggable:false,
animation: google.maps.Animation.DROP
});
});
}
EDIT2:
Another thing to try is rename your functions.js to function.js.php, update any references to it and then try that - then it would hopefully run through the php pipeline and run the php code in your js file.

Related

Adding places to google maps

I have a php application that stores Lng-Lat Coordinates to my database.
I would like to show all these places to a google map.
Edit: I have 6000 coordinates, I would like to do this in some way automatically.
Thank you
There are articles for that, which you can find nice and easily on Google
https://developers.google.com/maps/articles/phpsqlajax_v3
If you have several locations, you can use the following code:
var coords = [
[40.980542, 55.111786],
[42.329036, 55.222452],
[44.280249, 54.333]
];
function initialize() {
var myLatlng = new google.maps.LatLng(coords[0][0], coords[0][1]);
var myOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), myOptions);
for (var i = 0; i < coords.length; i++) {
var latlng = new google.maps.LatLng(coords[i][0], coords[i][1]);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "marker : " + (i + 1)
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
Check out a working example in JSfiddle.
Also, take a look at Google Places API.
Its a service that returns information about Places using HTTP requests

Retrieve remote JSON content with jQuery

I have the problem of retrive a Json into my Jquery script.
A php script, located at http://myserver.com/script.php return by echo a JSON like:
{"locations":[{"name":18492554,"lat":"12345","long":"234"},{"name":18492553,"lat":"4567","long":"234},{"name":18492555,"lat":"2234","long":"234}]}
I want to plot that point into my Jqueru script like:
(function() {
window.onload = function() {
// Creating a new map
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(41.6, -0.88),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
///////////////////// GET the JSON data ///////////////////
var json = // ???????
// Creating a global infoWindow object that will be reused by all markers
var infoWindow = new google.maps.InfoWindow();
// Looping through the JSON data
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.long);
// Creating a marker and putting it on the map
//var iconBase = 'https://dea-srl.net/domenico/traking/js/';
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.nombre,
icon: iconBase + 'schools_maps.png'
});
// Creating a closure to retain the correct data, notice how I pass the current data in the loop into the closure (marker, data)
(function(marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.nombre);
infoWindow.open(map, marker);
});
})(marker, data);
}
}
})();
My problem is get that Json into de jquery. It is possible?
I tryed using get metho like:
$.get(" http://myserver.com/script.php");
but it doesnt works.
Any idea about that? Thanks in advance.
What you mean by doesn't work? What errors you have?
Are you using the done function?
$.get(" http://myserver.com/script.php").done(function(data) {
console.log(data);
});
or you can use directly the $.getJSON function.
$.getJSON('http://myserver.com/script.php', function(data) {
var json = data;
});
To load the json data.
If there is any other issue, you have be a bit more precise.

I'm trying to use PHP to add markers to Javascript (Google Maps) but it isn't working the way I have indended it

I'm trying to use PHP to add a custom marker using GET. I can get inside the if statement just fine and the map loads, but this doesn't add a marker, I'm not familiar with Javascript I'm just using the documentation to do what I need to do.
Inside autolocategmap.js it just contains the Javascript to initialize the map and use geolocation to find the user and it works great, the only problem is the marker is not appearing on load or refresh or anything, I'm not even sure if I can append this extra bit of script by just including <script>custom marker</script>, any information would be great thanks.
<?php
/* Include header and config and set variable*/
require_once('config.inc.php');
require_once($rootdir . $dirsubfolder . 'navbar.php');
$route = $_GET['route'];
?>
<?php
/* User wants to retrieve their route */
if ((isset($route)) && (strcmp($route, "sunauto") == 0)) {
?>
<script src="js/autolocategmap.js"></script>
<script>
addMarker('56.742111','-111.481753','Stop 3', 'Arrives at: 6:00am');
</script>
<?php
}
?>
autolocategmap.js:
/**
* Basic Map
*/
$(document).ready(function(){
var map = new GMaps({
div: '#gmap',
lat: 56.744901,
lng: -111.473049,
zoom: 16,
zoomControl : true,
zoomControlOpt: {
style : 'SMALL',
position: 'TOP_LEFT'
},
panControl : false,
});
GMaps.geolocate({
success: function(position) {
map.setCenter(position.coords.latitude, position.coords.longitude);
},
error: function(error) {
alert('Geolocation failed: '+error.message);
},
not_supported: function() {
alert("Your browser does not support geolocation");
}
});
$(window).resize(function () {
var h = $(window).height(),
offsetTop = 150; // Calculate the top offset
$('#gmap').css('height', (h - offsetTop));
}).resize();
});
function addMarker(lat,lng,title,window){
map.addMarker({
lat: lat,
lng: lng,
title: title,
infoWindow: window
});
}
function show_map() {
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(51.477118, -0.000732),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var checkCoords = new Array();
checkCoords[0] = addMarker(51.477118, -0.000732, 'Royal Observatory, Greenwich, London', map);
checkCoords[1] = addMarker(38.92126, -77.066442, 'US Naval Observatory, Washington, DC', map);
checkCoords[2] = addMarker(48.853499, 2.348090, 'Notre Dame Cathedral, Paris', map);
}
function addMarker(lat, lng, title, map) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
title: title
});
marker.setMap(map);
return (lat + ',' + lng);
}
show_map();
Ok, use that for your js file. It is straight javascript, no jQuery, but it does what you want. You can then play with it to your hearts content.
As for multiple markers. There are many ways they can be handled through loading from whatever sources.
Maybe a good bet would be for the php to create a json feed that the javascript could read in and then loop through.

how to get the description inside the popup when i click on marker in a map

I have 2 tables and i have mentioned the fields of it,
1. events:event_id,title,location,latitude,longitude,address,description,link
2. event_time:event_id,start_time,end_time,start_date,end_date,date
i have given the my map code below in that i am trying to get the popup when the particular marker is clicked on the map.when i click on the marker it displays the popup and in popup we retrieve the table datas.
The problem what i have is, i am able to get all the data from database other than description. but when i try to retrieve description the map wont be shown.
the way data is retrieved from the database is also given below in the code.
<script src="http://maps.google.com/maps/api/js?v=3&sensor=false" type="text/javascript"></script>
<script type="text/javascript"><script language="javascript">
new google.maps.Size(32, 32), new google.maps.Point(0, 0),
new google.maps.Point(16, 32));
var center = null;
var map = null;
var markersArray = [];
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: info,
maxWidth: 500,
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup =null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
currentPopup.close();
currentPopup = null;
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("map1"), {
center: new google.maps.LatLng(12.972352762582736,77.59734949737549),
zoom:60,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
});
<?
$query=mysql_query("select * from events join event_time on (events.event_id=event_time.event_id) where events.isapproved='Y'");
while ($row = mysql_fetch_array($query))
{
$title=$row['title'];
$location=$row['location'];
$sdate=$row['start_date'];
$edate=$row['end_date'];
$stime=$row['start_time'];
$end_time=$row['end_time'];
$lat=$row['latitude'];
$lon=$row['longitude'];
$address=$row['address'];
$date=$row['date'];
$de=$row['description'];
$link=$row['link'];
echo ("addMarker($lat,$lon,'$stime ".to."$end_time<br/><br/><b>$title</b><br/><br/>$address<br/><br/>$de<br/><a>$link</a>');\n");
}
?>
center = bounds.getCenter();
map.fitBounds(bounds);
}
</script>
the map code and retriveing data and displaying it are together.
if anyone knows it,please help me solve this problem.thanks in advance.
I suggest checking the values for Description in your database. Are any characters which are Javascript special values escaped?
For instance, suppose the Description value for one record is:
You can't find a better party than this one!
If you put this in place of $de in your addMarker line above, and leave all the other variables alone, the resulting line of Javascript is:
addMarker($lat,$lon,'$stime to $end_time<br/><br/><b>$title</b><br/><br/>$address<br/><br/>You can't find a better party than this one!<br/><a>$link</a>');
Notice that the apostrophe in "can't" now ends the Javascript string. What the Javascript interpreter sees is code like:
addMarker($lat,$lon,'$stime to $end_time<br/><br/><b>$title</b><br/><br/>$address<br/><br/>You can'
t find a better party than this one!<br/><a>$link</a>');
The first line is an incomplete statement, and the second line starts with the second part of the $de value outside of quotes.
In general, almost all your variable values will be interpreted first as Javascript and then as HTML. Thus, you should escape them according to HTML conventions and then Javascript conventions, in order to be sure they don't disrupt anything.

Google Maps API v3 - Simple but add Geocode of address from php/mysql

I have this simple hello world version of a google map api javascript v3 and it works for a static geocode. My data is normal addresses (i.e. "30 rockefeller center, New York, NY").
This data is being called from with php from a mysql database. I can get the address on the page with something like this...For the purpose of this post, say this would have all info: address, city, state, zip code
<?php echo $row_query_details['address'];?>
So, I need to geocode this info for the map. I'm very comfortable with mysql and php, but not as much with javascript. I have been trial/error and researching this for a couple of days.
I have looked everywhere for a working sample or example and feel like this relatively simple problem must have been asked and answered many times over, but I cannot figure it out!
Thanks in advance.
Here is the code I'm working with:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var marker = new google.maps.Marker({
position: latlng,
title:"Hello World!"
});
// To add the marker to the map, call setMap();
marker.setMap(map);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:500px; height:500px"></div>
</body>
</html>
Hello and happy anniversary (regarding your question and tutorial).
I am a web-developer and must thank you. I used this tutorial as I currently do not have a way to geocode via submit (lat/long needs to be pulled from address stored in db) as I am consulting an existing site and have minimal access to backend code.
To answer your question regarding marker interactivity, this takes a few easy steps:
1) Provide some content. This is done before declaring the geocoder (var geocoder;):
var contentString =
'line 1'+
'line 2';
2) Underneath the marker declaration ( var marker = new google.maps.Marker({ ), you will need to declare infowindow and add the event listener:
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
Edit:
I have successfully pulled array information from a MySQL database by expanding on your method. My method is here:
1) Basic php below:
include (dbinfo.php)
$result = mysql_query( 'SELECT * FROM table')
$count = 0
2) Setting up google maps API:
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=yourkey&sensor=false">
</script>
3) Geocoding setup below:
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
var latlng = new google.maps.LatLng(yourlat, yourlong); //This is to center the map
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?php //Starts while loop so all addresses for the given information will be populated.
while($row = mysql_fetch_array($result)) //instantiates array
{ ?>
geocoder = new google.maps.Geocoder();
var address = '<?php echo $row['address'].', '.$row['city'].', '.$row['state'].', '.$row['zip'].', '.$row['country']; ?>';
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//marker generation is done though adding the primary ID to the "marker" variable, so if address "1" has the primary ID of "1", your marker would read "marker1"
var marker<?php print $row['primaryID']; ?> = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: "This can be a php variable or whatever you like. It is displayed on hover."
});
//var contentString manages what is seen inside of the popup
var contentString =
'line 1'+
'line 2';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker<?php print $row['primaryID']; ?>, 'click', function() {
infowindow.open(map,marker<?php print $row['primaryID']; ?>);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
<?php
$count++;
} //ends while
?>
}
/*end javascript*/
</script>
Thank you very much again for posting this. It was very useful.
You can use your PHP variable into JavaScript by passing php variables in function initialize().
your body tag will look like below;
For Ex:
<body onload="initialize('<?php echo $row_query_details['address'];?>')">
Then you will use this particular variable in your javascript code, your javascript function will look like below:
<script type="text/javascript">
function initialize(address) {
var G_address = address;
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var marker = new google.maps.Marker({
position: latlng,
title:"Hello World!"
});
// To add the marker to the map, call setMap();
marker.setMap(map);
}
</script>
Now you can use this G_address JavaScript variable dynamically in your G-MAP code..
This will be helpful to you..
So, I'm going to answer my own question here. The first answer provided I was not able to utlize. I'm not sure if the answer was incomplete or I just didnt' follow it. Regardless, here's what the code looks like:
First I had my address components pulling from the mysql db and I assigned them variables, like this:
$county = $row_qry['county'];
$address = $row_qry['address'];
$city = $row_qry['city'];
$state = $row_qry['state'];
Then, my google v3 stuff looks like this:
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(34.052234,-118.243685);
var address = '<?php echo $address.', '.$city.', '.$state; ?>';
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
And that sort of answers my question. There are a couple of issues I still need to resolve, such as (a) how to make the marker be clickable and interactive, and (b) the map flashes a the geocode first defined (34.05,-118.24) before showing the correct address.
Both of these issues I need to still resolve, but at least the geocoding is working successfully. Hope this helps someone else.
Thanks!

Categories