I have a Google Map which display fine (Google Maps API v3 - see code below). The code was initially inserted into the main index.php like so:-
<script type="text/javascript">
code here....
</script>
This works fine as inline code, and I can also use within index.php to insert variables from my PHP code into the Google Maps API.
As the code is growing I wanted to separate out the Google Maps API javascript and pop it into an external file for tidyness.
My first thought was to insert the file like so:
<script type="text/javscript" src="code/googlemaps.php"></script>
Now this works as it stands, however as soon as I try to insert any PHP code it wont work. I'm not too sure of how the PHP server handles the requests, but I guess I want the js file to be handed to the PHP parser and the PHP code to be parsed and the js with the parsed php then passed back to the browser.
The code is triggered by
<body onload="initialize()">
within my main index.php (im new to javascript so please bear with me).
For completeness here is the js code im using:
function initialize() {
// Main Google Map view variables
var mapOptions = {
zoom: 6,
center: new google.maps.LatLng(<?php echo $selected_lat . "," . $selected_lon; ?>),
mapTypeId: google.maps.MapTypeId.ROADMAP,
noClear: true,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.TOP_RIGHT
},
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.BOTTOM_RIGHT
},
streetViewControl: false
};
// Display Google Map
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
//Display Select Airport Marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(<?php echo $selected_lat . "," . $selected_lon; ?>),
map: map,
title:"<?php echo $airport_name[$selected_airport]; ?> Airport Reference Point\na new line\nanother line"
});
// google.maps.Circle variables
var seRangeOptions = {
center: new google.maps.LatLng(<?php echo $selected_lat . "," . $selected_lon; ?>),
fillOpacity: 0.3,
fillColor: "blue",
map: map,
radius: <?php echo seradius; ?>,
strokeColor: "#000000",
strokeOpacity: 0.0,
strokeWeight: 0
};
// display Google Maps circle
serangecircle = new google.maps.Circle(seRangeOptions);
}
ok, problem solved. Here is what I did, feedback welcome, I'm still learning :) Following code put into JavaScript file:
<?php session_start(); ?>
<?php echo 'var lat = "'.json_encode($_SESSION['lat']).'";';?>
Still a bit fuzzy on the order this all gets executed. I'm assuming PHP parses the javascript file, inserts the PHP variables and then returns the file to the browser? Also, any utilities like Firebug will let me see how this works in practice.
I also popped in the following at the top of the js file which seems to tidy-up how the source code is displayed in the browser too:
<?php header('Content-type: text/javascript'); ?>
The issue might be this line:
title:"<?php echo $airport_name[$selected_airport]; ?> Airport Reference Point\na new line\nanother line"
JavaScript doen't accept newlines to directly to continue the string, you must use \n, if title:"<?php echo $airport_name[$selected_airport]; ?> Airport Reference Point\na new line\nanother line" is returning a multiline String then it will break the JavaScript code.
Try to use the str_replace() function to replace all new lines to \n, and also addslashes() so " will not break the JavaScript String too
title:"<?php echo str_replace("\n", '\n', str_replace("\r",'', addslashes($airport_name[$selected_airport]))); ?> Airport Reference Point\na new line\nanother line"
Related
I've been using PHP simple HTML dom parser to parse some data from websites.
Say if there is a web page with a Google map on it and that map has marker on it indicated by a lat and long coordinate, is there a way of retrieving those coordinates from a JavaScript variable?
Here is an example of the JavaScript code I would like to get access to:
<script type="text/javascript">
function GMinitialize() {
var myLatlng = new google.maps.LatLng(11.11, -11.11);
var mapOptions = { zoom: 16, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP }
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var marker = new google.maps.Marker({ position: myLatlng, map: map });
} ;
</script>
If it's always going to be exactly the same structure just with different coordinates, as you suggested in your comment above, you could pull the text of the <script> tag with PHP Simple HTML DOM, then parse out the coordinates passed to the LatLng contructor with a regex...perhaps something very simple like:
/var myLatlng = new google\.maps\.LatLng\((.*)\)/
I am trying to figure out how to pass the latitude and longitude to a google map when my page loads. I am using the following code in the header of my page which works to generate the maps based on the hard-coded latitude and longitude:
var map1;
var map2;
$(document).ready(function(){
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(43.7620537, -79.3516683),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map1 = new google.maps.Map(document.getElementById("map-canvas-1"),myOptions);
var myOptions2 = {
zoom: 14,
center: new google.maps.LatLng(43.6918950,-79.5310706),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map2 = new google.maps.Map(document.getElementById("map-canvas-2"),myOptions2);
}
$("#maptabs").tabs({initialIndex:0,collapsible:true,select: function(){}});
In the body of the page I use the following PHP script to retrieve the correct latitude and longitude that I would like to map:
<?php
$google_maps_key='ABQIAAAAO-NJVsUOX31LQYJY1LUG8BSOYIDhzYrztjureJjDlAP7PmMi1xQsm9hQ6Z-LRdLFkCtIPr0FQBZxeQ';
$adr = urlencode(DLookup("Property Address", "tblproperties", "`Roll#`=".$id["pntysc"]["pn"]).", ".DLookup("municipalityname", "tblmunicipalities", "municipalitiescounty=".$county));
$url = "http://maps.google.com/maps/geo?q=".$adr."&output=xml&key=$google_maps_key";
$xml = simplexml_load_file($url);
$status = $xml->Response->Status->code;
if ($status='200') { //address geocoded correct, show results
foreach ($xml->Response->Placemark as $node) { // loop through the responses
$address = $node->address;
$quality = $node->AddressDetails['Accuracy'];
$coordinates = $node->Point->coordinates;
echo ("Quality: $quality. $address. $coordinates<br/>");
}
} else { // address couldn't be geocoded show error message
echo ("The address $adr could not be geocoded<br/>");
}
?>
Here is my question: How can I populate the maps using the $coordinates variable that is generated in the body of the page, when I have code in the header of the page that needs that particular value? What is the best practice in terms of populating the maps using variable latitude and longitude instead of having those values simply hard-coded?
Thanks.
You need to consider defining your Coordinates to display prior to displaying your header. That is, define everything your going to use in your google maps prior to anything being displayed. Place all data into arrays; $coordinates, $groups, etc. You don't have to build out an XML file. You can just use a mix of PHP to build out the Javascript used in your maps views. You can visit a WordPress example at:
http://www.dogfriendlyorlando.com/
There's an IFRAME in the page that displays the header map based on the information provided thru WordPress Posts.
I can't seem to paste in the entire code here.
Email me at jjwdesign - thru gmail and I'll send you the PHP code so you can look at it.
There's another more complex CRM example (SugarCRM - Google Maps project) at:
http://www.sugarforge.org/projects/jjwgooglemaps/
Cheers, Jeff Walters
I'm trying to use the Google Maps V3 API to create markers on a google map. I have the coordinates of the markers in mySQL database, and is currently in a PHP array in my .php file. Now how do I use a foreach() loop (or another suitable method) to loop through the elements in my PHP array and create a new google map marker with each iteration of the loop?
PS: My PHP is decent, but not my javscript knowledge. The tutorial I'm following now on creating the markers is at http://www.svennerberg.com/2009/07/google-maps-api-3-markers/
Code
I'm using Codeigniter framework, so the controller+model file already retrieved the necessary data(name, lng, lat...) into an array $map. I can loop the array using the usual method:
foreach($map as $row) {
$lng = $row[lng] // this is not necessary, its just to show what is in the array
$lat = $row[lat]
// now how do I use this loop to create new marker code in javascript?
}
The JS code for creating a google map marker which has to be created once per foreach loop iteration is like:
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: new google.maps.LatLng($lng, $lat), // how do i pass the PHP variables into the JS code?
mapTypeId: google.maps.MapTypeId.ROADMAP
});
So my question is how do i pass the PHP variables in the PHP array to create the JS code above, once per each foreach() loop iteration?
First of all, you are on the right track, but you just need to understand the separate concepts of server-side and client-side languages and how they can interact. PHP doesn't "pass" variables to JavaScript, but what it does do is generate whatever HTML document you want.
That HTML document then can contain JavaScript, which will execute as the page is rendered by the browser. So, think of your PHP as making the JavaScript code:
Example of PHP outputting JavaScript code in HTML page:
<script type="text/javascript">
var testval = "<?php echo "Hello, " . (5 + 3) . "!" ?>"; // "Hello, 8!
</script>
Now, I looked up the tutorial, and actually the code in your question is not the right code — instead it is the code to create the map, and the lat/long parameters in your example are for the center, not a marker.
So, in your PHP page, you want to do the following:
Somewhere, you need to create the map: var map = new google.maps.Map... (as shown in the tutorial)
Next, get the $map array with array items containing the 'lng' and 'lat' keys. (Note: you should always wrap array key names with quotes)
Inside an opened script tag use <?php to create a PHP code block, and create your foreach loop. For each item, create the JavaScript code needed to create the marker.
Example of foreach loop:
<script type="text/javascript">
<?php
foreach($map as $row) {
$lng = $row['lng'];
$lat = $row['lat'];
?>
// Creating a marker and positioning it on the map
new google.maps.Marker({
position: new google.maps.LatLng(<?php echo $lat ?>, <?php echo $lng; ?>),
map: map
});
<?php
}
?>
</script>
Usually the approach here is to encode the PHP data as JSON and then echo it into a Javascript variable:
<script type="text/javascript">
var myData = <?php echo json_encode($map); ?>;
</script>
which will output a Javascript literal you can use in your client-side scripting.
You'll want to loop this:
var marker;
<?php foreach($map as $row){ ?>
marker = new google.maps.Marker({
position: new google.maps.LatLng(<?php echo $row['lat'].','.$row['long']; ?>),
map: map
});
<?php } ?>
Just after the other code you included (which is to setup the map initially).
example to loop in JavaScript is as follows-
<script type="text/javascript">
"<?php echo $arr=array('1'=>'1','2'=>'2','3'=>'3','4'=>'4','5'=>'5');
foreach($arr as $k => $v){ ?>"
var x='<?php echo $v; ?>';
alert(x);
"<?php } ?>"
</script>
Replace $arr with your array and apply google map code in the script.
As #nrabinowitz said you can add the code in a ajax request
If your javascript is in the same page being loaded, you can add it in the same page.
<?php $c = 0;// counter ?>
<?php foreach ($map as $row):?>
var marker<?php echo $c?> = new google.maps.Marker({
position: new google.maps.LatLng(<?php echo $row['lat'].','.$row['long']; ?>), map: map });
<?php $c++; ?>
<?php endforeach;?>
THis way you wont overwrite the variable
Hi I have posted two values for latitute and longitute to a php page using a form, then on the php page I am displaying a googlemap and want to use the two values i posted as the latitude and longitute to plot on the map. I think iv done everything right but it doesnt seem to pick up the values.any ideas? cheers!
<script type="text/javascript">
function initialize() {
var lat= "<?php echo $_POST['coordinates']; ?>";
var long= "<?php echo $_POST['coordinatestwo']; ?>";
var latlng = new google.maps.LatLng(lat,long);
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,
map: map,
title: "Your current location!"
});
}
</script>
</head>
<body onLoad="initialize();">
long is a reserved word in JavaScript. Try lng (no 'o') as your variable name instead.
var lng= "<?php echo $_POST['coordinatestwo']; ?>";
If you view source in your browser, do you see the php values there? If not then there is something wrong with your form. We would need to see more code.
But chances are it's the long being a reserved word issue I mentioned above.
Don't use long as a variable name (it's a reserved word). Also, you don't need quotes around numeric values. Try this:
var lat = <?php echo floatval($_POST['coordinates']); ?>;
var lng = <?php echo floatval($_POST['coordinatestwo']); ?>;
EDIT: Tip - if you use a (good) editor with color highlighting and syntax checking for JavaScript, this is an error that would be highlighted (mine reports: "strict warning: long is a reserver identifier").
I have a working jsFiddle here:
http://jsfiddle.net/rcravens/RFHKd/
Mostly your code. I added the following:
A 'div' with an ID of map_canvas
A style to this div giving it width and height.
Included the script to load google maps.
Hope this helps.
Bob
#paul elliot: That doesn't look like all your code..? See this example to fill in the bits your code is missing: http://code.google.com/apis/maps/documentation/javascript/examples/map-simple.html
I have a MySQL database where I stored some marker position (along with some other information) which I loaded into google map. I followed the example -
http://code.google.com/apis/maps/articles/phpsqlajax.html
and it worked fine for me.
Now what I want to do is, suppose a user will be able to choose an id of a specific marker and clicking on a button it will be loaded onto the map. Not sure how to load the specific marker on the map dynamically.
Any sort of help will be appreciated.
I have set up an example here. I am using the Google Geocoding API to receive co-ordinates of the address entered by the user and creating the marker using Google API V3 as shown below
Ajax Request to get the co-ordinates
$.getJSON("getjson.php?address="+address,
function(data){
lat=data.results[0].geometry.location.lat;
lng=data.results[0].geometry.location.lng;
point= new google.maps.LatLng(lat,lng);
map.setCenter(point);
zoom = 14;
marker = createMarker(point,"<h3>Marker"+(markersArray.length+1)+" "+point+"</h3>",zoom);
});
PHP Code to return the co-ordinates
<?php
$address = $_GET['address'];
$address=str_replace(" ","+",$address);
if ($address) {
$json = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$address.
'&sensor=true');
echo $json;
}
?>
Creating the Marker
function createMarker(latlng, html,zoom) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
marker.MyZoom = zoom;
return marker;
}
First of all i see in your link that you use v2.Try to use v3 at least now that you are at the beginning since the v2 is deprecated.
As of your question i can only tell you the procedure and then you can make it happen.
1. User interaction
User interacts with UI and selects i.e. a range of prices(0-100).
2. Ajax request
The client sends an ajax request to server to get json with jquery getJson() or any other way.
3. Server Respond
A php page responds to your ajax call and make a query in mysql getting a resultset of position-markers,converts it in json and send it back.
4. Parse respond
Parse the json back to the client and create markers.
Hi I found this one great help
http://www.svennerberg.com/2012/03/adding-multiple-markers-to-google-maps-from-json/
Create a json object as given the link and pass it to javascript .
function createMarker(json){
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title
});
}
}