Gmap info box popup - php

Hi i have an web app where i integrate gmap on it which will look similar to Yelp gmap services. The issues is that when i mouseover the marker the infobox stuck within the box as follow:
the infobox suppose to look like this
Below are my current code for integrate gmap
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox_packed.js"></script>
<script type="text/javascript">
var gmap, gpoints = [];
$(document).ready(function() {
initialize();
});
function initialize() {
gmap = new google.maps.Map(document.getElementById('themap'), {
zoom: 8,
streetViewControl: false,
scaleControl: false,
center: new google.maps.LatLng(3.3000000,101.9629796),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
<?php
$content = '<p>Test</p>';
?>
gpoints.push( new point(gmap, '<?php echo $lat; ?>', '<?php echo $long; ?>', '<?php echo $content; ?>') );
}
function point(_map, lat, lng, content) {
this.marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
map: _map,
zIndex: 11
});
this.content = content;
var gpoint = this;
google.maps.event.addListener(gpoint.marker, 'mouseover', function() {
popup(gpoint);
});
google.maps.event.addListener(_map, 'zoom_changed', function() {
center=gpoint.marker.getPosition();
lat=center.lat();
lng=center.lng();
// alert(lat+"===="+lng);
});
}
function popup(_point) {
_point.popup = new InfoBox({
content: _point.content,
position: _point.marker.getPosition(),
// shadowStyle: 1,
padding: 20,
//backgroundColor: '#ddd',
borderRadius: 10,
arrowSize: 10,
borderWidth: 1,
// borderColor: '#dddddd',
disableAutoPan: true,
arrowPosition: 30,
// backgroundClassName: 'phoney',
arrowStyle: 2
});
_point.popup.open(_point.marker.map, _point.marker);
google.maps.event.addListener(_point.popup, 'domready', function() {
google.maps.event.addDomListener(_point.marker, 'mouseout', function() {
_point.popup.close();
});
});
}
</script>

You may use the option pixelOffset of the infoBox to control the position related to the marker.
The default is 0,0 , which means that the top left corner of the infoBox sticks on the position(of the marker).
To place it top+center, you must explicitly assign to the content of the infobox, and apply a pixelOffset as follows:
pixelOffset:new google.maps.Size(-halfOfWidthOfTheBox,0)
When you don't know the size of the infoBox you may calculate it.
Add this to the domready-callback of _point.popup:
this.setOptions({pixelOffset:new google.maps
.Size(-parseInt(this.div_.offsetWidth/2,10),0)});

Related

Google Map pop -up windows doesn't show anything inside it

i am using PHP MYSQL on WordPress with Google Map API where the code retrieve data from the MYSQL database and display markers on the map based on the existing coordinates in the database. also it display a infowindow on click Listener.
the problem is that the infow window doesn't shows any data inside of it.
can anyone one tel me where is the error?
code:
<?php
/*
Template Name: MAP2
*/
get_header();
?>
<!DOCTYPE html>
<html>
<head>
<title>Custom Markers</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=**********&callback=initMap">
</script>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 600px;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map,currentPopup;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: new google.maps.LatLng(33.888630, 35.495480),
mapTypeId: 'roadmap'
});
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var icons = {
parking: {
icon: iconBase + 'parking_lot_maps.png'
},
library: {
icon: iconBase + 'library_maps.png'
},
info: {
icon: iconBase + 'info-i_maps.png'
}
};
function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
//icon: icons[feature.type].icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: feature,
maxWidth: 300
});
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() {
map.panTo(center);
currentPopup = null;
});
}
var features = [
<?php
global $wpdb;
$prependStr ="";
foreach( $wpdb->get_results("SELECT siteID, latitude, longitude FROM site_coordinates2", OBJECT) as $key => $row) {
$latitude = $row->latitude;
$longitude = $row->longitude;
$info = $row->siteID;
echo $prependStr;
?>
{
position: new google.maps.LatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>),
}
<?php
$prependStr =",";
}
?>
];
for (var i = 0, feature; feature = features[i]; i++) {
addMarker(feature);
}
}
</script>
</body>
</html>
<?php
get_footer();
?>
If I'm reading your code right, you've got an array of features that looks like:
features = [
{position: new google.maps.LatLng(1, 2)},
{position: new google.maps.LatLng(3, 4)},
// etc...
];
i.e. the array contains objects with just a position property. So you correctly refer to that when you do:
position: feature.position,
However when you try and set your infowindow content using:
new google.maps.InfoWindow({
content: feature,
maxWidth: 300
})
That won't work, because the content property is meant to be a string, not a JS object. You need to specify some text there. If you're just wanting to display the coordinates, you could do:
new google.maps.InfoWindow({
content: feature.position.toString(),
maxWidth: 300
})

How to show multiple areas by location in google maps using php

Here is the Initialise function.....
function initialize() {
Here the variables $Latitude,$Longitude are array values so how can i store them in Javascript Variables so that they can store the above array values....
var lat='<?php echo $Latitude?>';
var lon='<?php echo $Longitude?>';
var latlng = new google.maps.LatLng(lat,lon);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
Here how can i loop the geocoder to show multiple areas using above array variables...
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder = new google.maps.Geocoder();
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Hello World!"
});
}
Its my sample code to plot multiple areas in google map by using area name or lat,lng.
var map;
var geocoder;
var marker;
var people = new Array();
var latlng;
var infowindow;
$(document).ready(function() {
ViewCustInGoogleMap();
});
function ViewCustInGoogleMap() {
var mapOptions = {
center: new google.maps.LatLng(11.0168445, 76.9558321), // Coimbatore = (11.0168445, 76.9558321)
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
// Get data from database. It should be like below format or you can alter it.
var data = '[{ "DisplayText": "adcv", "ADDRESS": "Jamiya Nagar Kovaipudur Coimbatore-641042", "LatitudeLongitude": "10.9435131,76.9383790", "MarkerId": "Customer" },{ "DisplayText": "abcd", "ADDRESS": "Coimbatore-641042", "LatitudeLongitude": "11.0168445,76.9558321", "MarkerId": "Customer"}]';
people = JSON.parse(data);
for (var i = 0; i < people.length; i++) {
setMarker(people[i]);
}
}
function setMarker(people) {
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
if ((people["LatitudeLongitude"] == null) || (people["LatitudeLongitude"] == 'null') || (people["LatitudeLongitude"] == '')) {
geocoder.geocode({ 'address': people["Address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false,
html: people["DisplayText"],
icon: "images/marker/" + people["MarkerId"] + ".png"
});
//marker.setPosition(latlng);
//map.setCenter(latlng);
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(this.html);
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
}
else {
alert(people["DisplayText"] + " -- " + people["Address"] + ". This address couldn't be found");
}
});
}
else {
var latlngStr = people["LatitudeLongitude"].split(",");
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
latlng = new google.maps.LatLng(lat, lng);
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false, // cant drag it
html: people["DisplayText"] // Content display on marker click
//icon: "images/marker.png" // Give ur own image
});
//marker.setPosition(latlng);
//map.setCenter(latlng);
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(this.html);
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
}
}
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyA7IZt-36CgqSGDFK8pChUdQXFyKIhpMBY&sensor=true" type="text/javascript"></script>
<div id="map-canvas" style="width: 800px; height: 500px;">
</div>
This should work for you assuming lat and lon are javascript arrays with the same length:
var map = null;
function initialize() {
var lat='<?php echo $Latitude?>';
var lon='<?php echo $Longitude?>';
// initialize map center on first point
var latlng = new google.maps.LatLng(lat[0],lon[0]);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var bounds = new google.maps.LatLngBounds();
for (var i=0, i<lat.length; i++) {
var latlng = new google.maps.LatLng(lat[i],lon[i]);
bounds.extend(latlng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Hello World!"
});
}
// zoom and center the map to show all the markers
map.fitBounds(bounds);
}
<?php
/* lat/lng data will be added to this array */
try{$work=$_GET["service"];}catch(Exception $e){echo 'Authorization Failed.Map may Misbehave or Buggy.Click here to report this';}
$locations=array();
$uname="root";
$pass="";
$servername="localhost";
$dbname="bcremote";
$db=new mysqli($servername,$uname,$pass,$dbname);
$query = $db->query('SELECT * FROM location');
while( $row = $query->fetch_assoc() ){
$name = $row['uname'];
$longitude = $row['longitude'];
$latitude = $row['latitude'];
/* Each row is added as a new array */
$locations[]=array( 'name'=>$name, 'lat'=>$latitude, 'lng'=>$longitude );
}
//echo $locations[0]['name'].": In stock: ".$locations[0]['lat'].", sold: ".$locations[0]['lng'].".<br>";
//echo $locations[1]['name'].": In stock: ".$locations[1]['lat'].", sold: ".$locations[1]['lng'].".<br>";
?>
<script>
//var myLatLng = {lat: -25.363, lng: 131.044};
function initMap() {
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
scrollwheel: false,
zoom: 4
});
<?php for($i=0;$i<sizeof($locations);$i++)
{ ?>
var marker = new google.maps.Marker({
map: map,
position: {lat: <?php echo $locations[$i]['lat']?>,lng: <?php echo $locations[$i]['lng']?>},
title: 'Service'
});
<?php } ?>
}
</script>
This code Snippet uses Dynamic Content without using JSON or XML. This below code is what we see in the Browser View Source tool. Hope this helps you...
<script>
//var myLatLng = {lat: -25.363, lng: 131.044};
function initMap() {
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
scrollwheel: false,
zoom: 4
});
var marker = new google.maps.Marker({
map: map,
position: {lat: 192.652.231.25,lng: 192.652.231.25},
title: 'Service'
});
var marker = new google.maps.Marker({
map: map,
position: {lat: 192.652.231.25,lng: 192.652.231.25},
title: 'Service'
});
}
</script>
UPDATE 2017
Google maps now supports the creation of maps with multiple locations which you can embed via iframe! Source: https://www.create.net/support/218-how-to-pin-point-multiple-locations-on-google-maps.html
Go to https://www.google.com/maps
Make sure you're signed in - you can do so by clicking the Login button in the top-right corner.
In the top left corner, next to the search box, click the menu icon to expand the menu
Click "Your Places", "Maps" and then click "Create Map" to edit your map.
A new window will pop up. Give your map a title and description, then click "Save".
You can now pinpoint locations manually by clicking the marker icon and placing it directly onto the map, or search for locations using the search box at the top of the screen.
If you're adding locations manually, you can name the location and save to add it to the map. If you're searching and adding specific locations, a green marker will appear on the map and you can click the 'Add to map' link.
Repeat steps 6 and 7 for each location you wish to plot.
Once you have done that save your map again and refresh the page. Then, to get the code to embed your map on to your Create website, please follow these steps:
Make sure you map is public. You can do this by clicking 'Share' beneath the map name.
Under 'Who has access' click 'Change' and make turn it 'On - Public on the web' and save.
Next, click the menu icon and click on the link 'Embed on my site'
The code will then pop up in a new window.
To use this, you will need to paste the code into an HTML fragment on your Create account, and then place the HTML fragment on your chosen page.
Example:
<iframe src="https://www.google.com/maps/d/embed?mid=1tX88xmVMIFW9DQneDff_ZMJtekc" width="100%" height="480"></iframe>

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.

Google maps API locking the zoom level of the whole webpage on the Iphone?

I have implemented a styled google map into my website, when I view the page on an iphone it locks the zoom level of the web page. The "map" is still "pinchable" to zoom but the webpage is not.. I can't work out how to turn on the pinch zoom for the webpage and the map?
Thanks in advance any helpers! Here's a link to the page - http://esdaledesigns.com/contact.php
<script type="text/javascript">
function initialize() {
// Create an array of styles.
var styles = [
{
"stylers": [
{ "hue": "#ff6e00" },
{ "saturation": -67 }
]
}
];
// Create a new StyledMapType object, passing it the array of styles,
// as well as the name to be displayed on the map type control.
var styledMap = new google.maps.StyledMapType(styles,
{name: "The Stockwell"});
// Create a map object, and include the MapTypeId to add
// to the map type control.
var mapOptions = {
zoom: 16,
center: new google.maps.LatLng(51.890488, 0.899154),
mapTypeControlOptions: {
mapTypeIds: ['map_style'],
},
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var myLatlng = new google.maps.LatLng(51.890488, 0.899154);
var marker = new google.maps.Marker({
position: myLatlng,
animation: google.maps.Animation.DROP,
map: map,
title:"The Stockwell"
});
//information
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h2 id="firstHeading" class="firstHeading">The Stockwell Colchester</h2>'+
'<div id="bodyContent">'+
'<p>THE STOCKWELL<br />18 WEST STOCKWELL STREET<br />COLCHESTER<br />ESSEX<br />CO1 1HN<br /></p>'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
//Associate the styled map with the MapTypeId and set it to display.
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
}
</script>
ok, worked it out....
It was this bit of code a few lines above the script I posted, just above the google api key. <meta name="viewport" content="initial-scale=2.0, user-scalable=no" /> I changed user-scalable to "yes" and initial-scale to "0.5" and everything is working correctly.
Hope this helps someone else.

How to know is marker inside polygon in google maps api

When You click on anywhere in map 1 new marker created and make polygon
its working fine but now my problem is i can't get is my marker which is coming from database is inside polygon or not, how to know it???
<?php include("config.php"); ?>
<?php $result = mysql_query("select * from `googlemaps`"); ?>
<html>
<head>
<title>Google Maps</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var poly, map;
var markers = [];
var path = new google.maps.MVCArray;
function initialize() {
var LatLng = new google.maps.LatLng(23.183, 75.767);
map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: LatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
function createMarker(point, title) {
var infowindow = new google.maps.InfoWindow({
content: "<span style='color:blue;'>"+title+"</span>"
});
var marker = new google.maps.Marker({
position: point,
map: map,
title:title
});
marker.Image ='https://d3szoh0f46td6t.cloudfront.net/public/1626980/small';
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map,marker);
});
return marker;
}
<?php
if(mysql_num_rows($result)>0)
{
while( $data = mysql_fetch_array($result) )
{ ?>
createMarker(new google.maps.LatLng(<?php echo $data['lat']; ?>, <?php echo $data['lon']; ?>), "<?php echo $data['title']; ?>");
<?php }
}
?>
poly = new google.maps.Polygon({
strokeWeight: 3,
fillColor: '#5555FF'
});
poly.setMap(map);
poly.setPaths(new google.maps.MVCArray([path]));
google.maps.event.addListener(map, 'click', addPoint);
}
function addPoint(event) {
path.insertAt(path.length, event.latLng);
var marker = new google.maps.Marker({
position: event.latLng,
map: map,
draggable: true
});
markers.push(marker);
marker.setTitle("#" + path.length);
google.maps.event.addListener(marker, 'click', function() {
marker.setMap(null);
for (var i = 0, I = markers.length; i < I && markers[i] != marker; ++i);
markers.splice(i, 1);
path.removeAt(i);
}
);
google.maps.event.addListener(marker, 'dragend', function() {
for (var i = 0, I = markers.length; i < I && markers[i] != marker; ++i);
path.setAt(i, marker.getPosition());
document.getElementById("abc").innerHTML=path.setAt(i, marker.getPosition());
}
);
}
</script>
</head>
<body style="margin:0px; padding:0px;" onLoad="initialize()">
<div id="map" style="width:500px; height:500px;"></div>
<div id="abc"></div>
</body>
</html>
You might be asking how to check this javascript or php. I am not aware of a GIS framework in these areas.
Most of the spatial databases (like SQL Server/Postgresql which I have worked with) provide features like ST_Contains or ST_Distance which you can make use of. I think this is part of OpenGIS specification.
I think you might probably be using MYSQL. So may just need to search for a function.

Categories