How can I show more details of one marker? - php

What I have:
The markers was created by a form submission, the form contains a postcode input. The below javascript will take this postcode and display as markers on google map. (this is a different page)
page1.php (code below)I have a php array, this array contains all infoWindow data and the javascript is to create map, markers and inforwindows.
<?php
..............
$info= array();
foreach($details as $d) {
$info[] = "<div id='infoData'>".$d['name'].$d['quantity']."<button id='details' onclick='window.location.href= \\\"page2.php\\\"'>Detail</button>"."<div>";
}
//.........
?>
The above code is everything on the infoWindow. Click that button in the products array will going to page2.php
<script>
//...................
function init() {
var mapDiv = document.getElementById("map");
var mapOptions = {
center: new google.maps.LatLng(51.528308,-0.3817765),
zoom: 12,
mapTypeId: 'roadmap'
};
var map = new google.maps.Map(mapDiv, mapOptions);
///////////////add markers//////////
var addressArray = ("abc", "def","xxx"), infoArray = (<?php echo $i; ?>);
var geocoder = new google.maps.Geocoder();
for (var i = 0, j=addressArray.length; i < j; i++) {
var info = infoArray[i];
geocoder.geocode({'address': addressArray[i]}, createCallback(info, map));
} //callback function
}
function createCallback(info, map) {
var callback = function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: 'Click for more details'
});
//..................
</script>
What I want to achieve:
page2.php I want to show more details of that page1.php button in infowindow I just clicked. How should I do this? Any hint??
I wrote php code on page two, but I just getting all records out,
there's no associations between that marker just clicked and the page2 record. How can I achieve this? page two do not contain any map, just purely text data.

In your code you can pass a unique key or id of that record you want to show on page2.php and get that id using $_GET method and use to show details of that marker.
on page1.php
<?php
..............
$info= array();
foreach($details as $d) {
$info[] = "<div id='infoData'>".$d['name'].$d['quantity']."<button id='details' onclick='window.location.href= \\\"page2.php?marker=".$d['id']."\\\"'>Detail</button>"."<div>";
}
//.........
?>
on page2.php
$infomarker = $_GET['marker'];
Use $infomarker to get the all the details.

Related

How to add star rating in google map api infowindow?

I am working on a wordpress site that will use a google map api, but i encounter a problem by adding rating widget in the google map infowindow. The rating criteria is showing but not the star.
Here is the screenshot
and here is my code
<script type="text/javascript">
jQuery(function($) {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
});
function initialize() {
var map, casino_name, lat, longt ;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
// Multiple Markers
var markers = [
//[casino_name, lat, longt],
<?php
$tooltip = '';
$args = array(
'post_type' => 'page',
'post_parent' => get_the_ID(),
);
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$post_id = get_the_ID();
echo "['".$casino_name = get_field('casino_name', $post_id)."', ".get_field('latitude', $post_id).', '.get_field('longitude', $post_id).']';
$rating = do_shortcode('[ratingwidget type="page" post_id='.get_the_ID().']');
$tooltip .= "['".'<img src="'.get_field('casino_logo', $post_id).'" alt=""/>'." ".'<a class="casino-link" href="'.get_field('casino_link', $post_id).'">'.get_field('casino_name', $post_id).'</a>'." ".$rating."']";
if (($the_query->current_post +1) != ($the_query->post_count)){
echo ',';
$tooltip .= ',';
}
wp_reset_postdata();
}
}
/* Restore original Post Data */
wp_reset_postdata();
?>
];
// Info Window Content
var infoWindowContent = [
<?php echo $tooltip; ?>
];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow();
var marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
console.log(infoWindow);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});
}
</script>
To implement Info Box instead of the standard Info Window, first add the InfoBox JS to your site.
Set the options for your Info Box based on the list of options in the properties table at the bottom of this page.
Here's a quick example, these options can go anywhere in your maps code:
// Set infobox options
var boxOptions = {
boxClass: "box-styles", /* Applies a class to your box for styling */
zIndex: 9999,
boxStyle: {
opacity: 0.75,
width: "222px"
},
closeBoxMargin: "10px",
closeBoxURL: "/assets/img/icons/cancel.png",
}
Then in your code, just replace:
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow();
With:
// Display multiple markers on a map
var infoBox = new InfoBox(boxOptions);
Then replace each instance of InfoWindow() with InfoBox() in your click event like so:
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoBox.setContent(infoWindowContent[i][0]);
infoBox.open(map, marker);
console.log(infoBox);
}
})(marker, i));
The above should give a rough idea of how to implement this. If your still having trouble - I suggest you create a fiddle with your code and work from that. Hope this helps.
Also have a look at the examples here: http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/docs/examples.html

Gmap3 show all the available markers on the map from database?

I am using gmap3 plugin to show google map. In my case I have stored all the information of properties in the database(mysql) with custom markers. Now I want that when the page is loaded it will display all the markers in google map.
For loading googlemap with gmap3 plugin I am using this code
function loadMap() {
jQuery(document).ready(function(){
if(typeof gMap == 'undefined') {
//// CREATES A MAP
gMap = jQuery('#map-canvas');
gMap.gmap3({
map: {
options: {
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
scrollwheel: true,
streetViewControl: false
}
}
});
}
});
}
and inside div ``map-canvas I can see the map. But can some one kindly tell me how to show all the markers with the positions? Any help and suggestions will be really appreciable. Thanks.
Update
If I am wrong with my codes then someone can show their codes to me. I am using Gmap3 plugin.
I am not sure about this it will work in gmap3 but i use this code for creating my costome icon hope it will help you
In the index.php use this for creating your costom icon pathlike this
<?php
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
$a=array();
while ($row = #mysql_fetch_assoc($result)){ $a='$row[\'type\']'=>array('icon'=>'$row[\'path\']','shadow'=>'$row[\'path2\']')
}
$a=json_encode($a);
?>
it should be done before js file after that
write this
<script>
var customIcons= <?php echo $a; ?>;
</script>
and finally load your map and infoWindowbox() in that function
function infoWindowbox() {
downloadUrl("xml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow,
animation: google.maps.Animation.DROP
});
markerArray.push(marker);
bounds.extend(marker.position);
bindInfoWindow(marker, map, infoWindow, html);
}
map.fitBounds(bounds);
// var markerCluster = new MarkerClusterer(map, markerArray);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
gmap3 initializator has a marker attribute that allows you to create markers.
See example with single and multiple markers here:
http://gmap3.net/en/catalog/10-overlays/marker-41
I think this example might help.
Updated:
If you want to read the data like from database (or) xml, You can then make an ajax request to that page (from any page on your site) using jQuery:
I have an example but this is with xml to get the data from xml file.
$.ajax({
url: 'categories.xml (or) your database path',
type: 'get',
success: function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new GLatLng(lat,lng);
var address = markers[i].getAttribute("address");
var name = markers[i].getAttribute("name");
var html = "<b>"+name+"<\/b><p>"+address;
var category = markers[i].getAttribute("category");
// create the marker
var marker = createMarker(point,name,html,category);
map.addOverlay(marker);
}
// == show or hide the categories initially ==
show("theatre");
hide("golf");
hide("info");
// == create the initial sidebar ==
makeSidebar();
});
});
Like this you may get the data from database also through using queries. Try this one atleast you may get the idea.
The gmaps3 plugin documentation shows how to add markers. If you create an options array in php through ajax/json and feed that to the markers: option your markers should be added.

Calling a JavaScript function in PHP for Google Map

hopefully you can help me. I have read a lot of forums regarding this but still cannot get what I wanted. I'm using PHP/MySQL to run my system. I already had a code in JavaScript that will allow the user to add a place and the system can add that place in the Google Map (embedded in my site) as a marker. Now, what I wanted is to add the coordinates of that new place in my database and then my map will just get the markers from the database for adding in the map.
Currently, what I did is to get the latitude and longitude of the added place from the javascript then was able to pass them to my php script within the same file. The latitude and longitude can be added in my database but I do not know now how to go back again to JavaScript so that I can add my markers.
What is the best way to do this? Is/Are there better approaches to solve this?
<?php
$marker = array();
if(isset($_GET['set'])){
$lat = $_GET['lat'];
$long = $_GET['longi'];
$newadd = $_GET['newAdd'];
$connect = mysql_connect("localhost","root","");
mysql_select_db("mapping");
$query=mysql_query("INSERT INTO markers VALUES('','','$newadd','$lat','$long','')");
}
?>
My JavaScript to place markers
function addMarkers(){
var tempMarker;
var tabs = [];
var blueIcon = new GIcon(G_DEFAULT_ICON);
blueIcon.image = "http://maps.google.com/mapfiles/ms/micons/green-dot.png";
// Set up our GMarkerOptions object
markerOptions = { icon:blueIcon };
// for loop get data from db and loop it
tempMarker = new GMarker(tempLatLng,markerOptions);
//if(tabs.length==0){
tabs[ctr] = [new GInfoWindowTab('Greetings','Hi! Welcome'), new GInfoWindowTab('My Info',tempMarker.getLatLng().toString())];
//}
tabInfoWindow(tempMarker,tabs, ctr);
markerArray.push(tempMarker);
displayMarkers();
}
}
Thanks!
Using jquery you can post the data in an ajax request and continue adding the markers in the success handler.
var location = {lat:56, lng:67, name:"my_place"};
$.ajax({
url: "save_place.php",
data: location,
dataType:"json",
success: function(response){
if(response.success){
// add marker to map here
}else{
alert("Error adding location to database");
}
},
error:function(){
alert("Error in connecting to server");
}
});
EDIT:
From your comments, I understand what you need is this one:
<?php
$lat = isset($_GET['lat']) ? $_GET['lat'] : 0;
$long = isset($_GET['longi']) ? $_GET['longi'] : 0;
$newadd = isset($_GET['newAdd']) ? $_GET['newAdd'] : "";
?>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type='text/javascript' src="http://maps.google.com/maps/api/js?sensor=false&.js"></script>
<style type='text/css'>
#map {
width: 400px;
height: 400px;
}
</style>
</head>
<body>
<div id="map"></div>
<script type='text/javascript'>//<![CDATA[
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(55, 11),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
function addMarker(lat, lng, newAdd) {
alert(" Adding marker " + lat + "," + lng);
this.lat = lat;
this.long = lng;
var location = new google.maps.LatLng(lat, long);
var marker = new google.maps.Marker({
position: location,
title: name,
map: map,
draggable: true
});
map.setCenter(location);
}
<?php
echo "addMarker($lat, $long, '$newadd')";
?>
</script>
</body>
</html>
url : http://<domain>/test.php?lat=40.735812&longi=-74.001389&newAdd=
Well what I do is have a endpoint on the PHP side that I can ask for the markers. Then when my map has loaded I will make a call to get them and then add them on:
$.post('/server/getMarkers',{},function(markers) {
for(var i=0; i < markers.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(marker[i].latitude, marker[i].longitude),
id:marker[i].id
});
google.maps.event.addListener(marker, "click", function() {
//request data for this.id to show in info window if needed
});
}
});
The getMarkers method on the PHP side could look something like this
public function getMarkers() {
/* fetch an array of markers details from the db by any means... */
$markers = getMarkersFromDB();
foreach ($markers as $key=> $marker) {
$payload[$key]['latitude'] = $marker->latitude;
$payload[$key]['longitude'] = $marker->longitude;
$payload[$key]['id'] = $marker->id;
}
echo json_encode($payload);
}

Getting error when trying to pass values from array to Google Maps Object

Im setting some json using wordpress post data on a page and then passing that json to some JS which loops through and adds markers to a map. I'm so close to getting it working, just need to figure out this last part.
My PHP code to create the json from an array:
<script type="text/javascript">
var markers = <?php echo json_encode($pageposts);?>
</script>
Here is my JS code:
var infowindow = null;
$(document).ready(function(){
initialize();
});
function initialize() {
var centerMap = new google.maps.LatLng(41.141208, -73.263726);
var options = {
zoom: 12,
center: centerMap,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map'), options);
setMarkers(map, markers);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
}
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i].meta_value),
map: map
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
//infowindow.setContent(this.html);
//infowindow.open(map, this);
});
}
}
If you want to see the page, with the json embedded - check out this link:
http://www.fairfieldctguide.com/test-map
view-source:http://www.fairfieldctguide.com/test-map
Any help would be greatly appreciated!
Jake
google.maps.LatLng expects two numbers as an argument. Currently you are passing in a string which will result in an error. So you need to convert your markers[i].metavalue to two numbers like so:
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
latlng = markers[i].meta_value.split(",")
lat = parseFloat(latlng[0])
lng= parseFloat(latlng[1])
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
//infowindow.setContent(this.html);
//infowindow.open(map, this);
});
}
}
If you don't want to do a converson you could just store lat and lng values as numbers in separate properties. So your json would look like this:
var markers = [{
"ID":"883",
"post_title":"Tucker's Cafe",
"meta_key":"meta_geo",
"lat":41.1674377,
"lng": -73.2236554
}
and you would add a marker like so:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i].lat, markers[i].lng),
map: map
});

Google Maps load issues on PHP page

I'm connecting a Google Map to a MySQL database to list distributors all over the world, and I seem to be having a few issues.
Sometimes the page itself will not load at all in Firefox (v4 on Mac). It's temperamental on my machine (FF v3.6 Mac) and a Windows machine (FF v4 Win 7), ok in Safari/Opera, doesn't load at all in IE 9 (Win 7). Not sure if it's a network issue or code.
Load time is pretty slow. Might be because the map covers the whole page (will create a square block to place it in).
The URL of the page is here and I used the code from Sean Feeney's page.
The code I have is:
<script src="http://maps.google.com/maps?file=api&v=2&key=<I entered my key here>" type="text/javascript"></script>
<body onUnload="GUnload()">
<div id="map" style="position:absolute;top:0px;bottom:0px;left:0;right:0;"></div>
</body>
<script type="text/javascript">
//<![CDATA[
var map;
var latlngbounds;
if (GBrowserIsCompatible()) {
function createMarker(point, address) {
var marker = new GMarker(point);
var html = address;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
function extendBounding(point) {
latlngbounds.extend(point);
var zoom = map.getBoundsZoomLevel(latlngbounds);
if (zoom < 10) {
zoom = 12;
}
map.setCenter(latlngbounds.getCenter(), zoom);
}
}
map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl3D());
map.addControl(new GMapTypeControl());
latlngbounds = new GLatLngBounds();
GDownloadUrl("genxml.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var address = markers[i].getAttribute("address");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, address);
map.addOverlay(marker);
extendBounding(point);
}
});
}
//]]>
</script>
The code that gets the data is the same as the example.
Any ideas as to why it doesn't always load in the browsers, and why it seems to take a while to load?
Thanks,
Adrian
Ideally you should wrap the code that loads the map inside a document ready or window load event.
I notice that your code is not nested properly inside the GBrowserIsCompatible() block so please fix that.
As far as I remember, Google maps API v2 requires you to call the setCenter() method before doing any operations on the map. So to begin with, set the center to (0, 0) immediately after creating the map.
I notice that you're downloading XML data before you add markers to the map. You must take into account the time taken by the server to serve the XML data. If you've called the setCenter() before downloading the XML, the map will display while the XML downloads asynchronously.
Inside the code that handles the XML data: when you add a marker, do not call setCenter() immediately. Doing so will cause the function to be called 1000 times if you have 1000 markers in your XML. Instead, just call latlngbounds.extend(point). Once you have iterated the loop, calculate the zoom/center and call setCenter(). This way you will end up calling this function only twice.
Edit
I've figured out what the problem is. The genxml.php randomly returns the string Google Geo error 620 occurred which cannot be parsed as XML which raises JavaScript errors and no markers are shown. Better have a look at the code of that file and see why this happens randomly. On other times when that file actually returns valid XML, the markers appear as expected.
It appears Google recently tightened geocoding requests. If you send 10 too fast, it cuts you off with 620 error. The solution they recommend is adding a dynamic timer. Other stackoverflow posts suggested a 0.25 second static timer was good enough, but I've found Google's recommendation of using a while loop that increments the timer value as needed works better. For example:
// Initialize delay in geocode speed
public $delay = 0;
public function lookup(arguments)
{
$geocode_pending = true;
while ($geocode_pending) {
$search = //address string to search;
$response = $this->performRequest($search, 'xml');
$xml = new SimpleXMLElement($response);
$status = (int) $xml->Response->Status->code;
switch ($status) {
case self::G_GEO_SUCCESS:
require_once('placemark.php');
$placemarks = array();
foreach ($xml->Response->Placemark as $placemark)
$placemarks[] = Placemark::FromSimpleXml($placemark);
$geocode_pending = false;
return $placemarks;
case self::G_GEO_TOO_MANY_QUERIES:
$delay += 100000;
case self::G_GEO_UNKNOWN_ADDRESS:
case self::G_GEO_UNAVAILABLE_ADDRESS:
return array();
default:
throw new Exception(sprintf('Google Geo error %d occurred', $status));
}
usleep($delay);
}
}
You can run your map code with window.load after everything is loaded:
jQuery(document).ready(function initAutocomplete() {
var p_lag=$('#longitude').val();
var p_lat=$('#latitude').val();
if(p_lat==''){
var p_lat=20.593684;
}
if(p_lag==''){
var p_lag=78.96288000000004 ;
}
var myLatLng = {lat: p_lat,lng: p_lag};
var map = new google.maps.Map(document.getElementById('dvMap'), {
center: myLatLng,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: myLatLng,
draggable: true,
map: map,
title: 'Map'
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
//map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function () {
searchBox.setBounds(map.getBounds());
});
//Click event for getting lat lng
google.maps.event.addListener(map, 'click', function (e) {
$('input#latitude').val(e.latLng.lat());
$('input#longitude').val(e.latLng.lng());
});
google.maps.event.addListener(marker, 'dragend', function (e) {
$('input#latitude').val(e.latLng.lat());
$('input#longitude').val(e.latLng.lng());
});
var markers = [];
// [START region_getplaces]
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
/*markers.forEach(function (marker) {
marker.setMap(null);
});*/
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function (place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
$('#latitude').val(place.geometry.location.lat());
$('#longitude').val(place.geometry.location.lng());
marker.setPosition(place.geometry.location);
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
});
}
);

Categories