<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Yelp Search API Example</title>
<style type="text/css">
html, body {width: 100%; height: 100%; font-family: arial;}
body {margin:0;padding 0;overflow: hidden;}
#mapContainer {padding-top: 50px;}
#map, #mapContainer {width:100%; height: 100%;}
#top {position:absolute; top:0; left:0; width: 100%; height: 50px; line-height: 50px;}
#spinner { visibility: hidden; margin-left:3px;}
#poweredby, #searchbox {line-height: 50px;}
#searchbox {text-align: center;}
#poweredby { float: right; margin-right: 3px;}
#poweredby img { vertical-align: baseline;}
.marker {font-size: 11px;}
.marker .businessimage { float: left;}
.marker .ratingsimage {vertical-align:middle; margin-top:0px;}
.marker .businessinfo { margin-left: 110px;}
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=[AIzaSyByEg0pBD4dGr3gZCk863XZZ0ZBkqhDhR4]"
type="text/javascript"></script>
<script type="text/javascript">
var YWSID = "aSVpoAZwxvtcwsscdWjBBw"; // common required parameter (api key)
var map = null;
var icon = null;
/*
* Creates the map object and calls setCenterAndBounds
* to instantiate it.
*/
function load() {
map = new GMap2(document.getElementById("map"));
GEvent.addListener(map, "load", function() {updateMap();});
map.setCenter(new GLatLng(40.296448,-79.478141),13);
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.setMapType(G_HYBRID_MAP);
if (window.attachEvent) window.attachEvent("onresize", function() { map.checkResize()} );
else if (window.addEventListener) window.addEventListener("resize", function() { map.checkResize()}, false);
// setup our marker icon
icon = new GIcon();
icon.image = "images/marker_star.png";
icon.shadow = "images/marker_shadow.png";
icon.iconSize = new GSize(20, 29);
icon.shadowSize = new GSize(38, 29);
icon.iconAnchor = new GPoint(15, 29);
icon.infoWindowAnchor = new GPoint(15, 3);
}
/*
* Construct the URL to call for the API request
*/
function constructYelpURL() {
var mapBounds = map.getBounds();
var URL = "http://api.yelp.com/" +
"business_review_search?"+
"callback=" + "handleResults" +
"&term=" + document.getElementById("term").value +
"&num_biz_requested=10" +
"&tl_lat=" + mapBounds.getSouthWest().lat() +
"&tl_long=" + mapBounds.getSouthWest().lng() +
"&br_lat=" + mapBounds.getNorthEast().lat() +
"&br_long=" + mapBounds.getNorthEast().lng() +
"&ywsid=" + YWSID;
return encodeURI(URL);
}
/*
* Called on the form submission: updates the map by
* placing markers on it at the appropriate places
*/
function updateMap() {
// turn on spinner animation
document.getElementById("spinner").style.visibility = 'visible';
var yelpRequestURL = constructYelpURL();
/* clear existing markers */
map.clearOverlays();
/* do the api request */
var script = document.createElement('script');
script.src = yelpRequestURL;
script.type = 'text/javascript';
var head = document.getElementsByTagName('head').item(0);
head.appendChild(script);
return false;
}
/*
* If a sucessful API response is received, place
* markers on the map. If not, display an error.
*/
function handleResults(data) {
// turn off spinner animation
document.getElementById("spinner").style.visibility = 'hidden';
if(data.message.text == "OK") {
if (data.businesses.length == 0) {
alert("Error: No businesses were found near that location");
return;
}
for(var i=0; i<data.businesses.length; i++) {
biz = data.businesses[i];
createMarker(biz, new GLatLng(biz.latitude, biz.longitude), i);
}
}
else {
alert("Error: " + data.message.text);
}
}
/*
* Formats and returns the Info Window HTML
* (displayed in a balloon when a marker is clicked)
*/
function generateInfoWindowHtml(biz) {
var text = '<div class="marker">';
// image and rating
text += '<img class="businessimage" src="'+biz.photo_url+'"/>';
// div start
text += '<div class="businessinfo">';
// name/url
text += ''+biz.name+'<br/>';
// stars
text += '<img class="ratingsimage" src="'+biz.rating_img_url_small+'"/> based on ';
// reviews
text += biz.review_count + ' reviews<br/><br />';
// categories
text += formatCategories(biz.categories);
// neighborhoods
if(biz.neighborhoods.length)
text += formatNeighborhoods(biz.neighborhoods);
// address
text += biz.address1 + '<br/>';
// address2
if(biz.address2.length)
text += biz.address2+ '<br/>';
// city, state and zip
text += biz.city + ', ' + biz.state + ' ' + biz.zip + '<br/>';
// phone number
if(biz.phone.length)
text += formatPhoneNumber(biz.phone);
// Read the reviews
text += '<br/>Read the reviews »<br/>';
// div end
text += '</div></div>'
return text;
}
/*
* Formats the categories HTML
*/
function formatCategories(cats) {
var s = 'Categories: ';
for(var i=0; i<cats.length; i++) {
s+= cats[i].name;
if(i != cats.length-1) s += ', ';
}
s += '<br/>';
return s;
}
/*
* Formats the neighborhoods HTML
*/
function formatNeighborhoods(neighborhoods) {
s = 'Neighborhoods: ';
for(var i=0; i<neighborhoods.length; i++) {
s += '' + neighborhoods[i].name + '';
if (i != neighborhoods.length-1) s += ', ';
}
s += '<br/>';
return s;
}
/*
* Formats the phone number HTML
*/
function formatPhoneNumber(num) {
if(num.length != 10) return '';
return '(' + num.slice(0,3) + ') ' + num.slice(3,6) + '-' + num.slice(6,10) + '<br/>';
}
/*
* Creates a marker for the given business and point
*/
function createMarker(biz, point, markerNum) {
var infoWindowHtml = generateInfoWindowHtml(biz)
var marker = new GMarker(point, icon);
map.addOverlay(marker);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(infoWindowHtml, {maxWidth:400});
});
// automatically open first marker
if (markerNum == 0)
marker.openInfoWindowHtml(infoWindowHtml, {maxWidth:400});
}
//]]>
</script>
</head>
<body onload="load()">
<div id="top">
<div id="poweredby">Powered by <img src="http://static.px.yelp.com/i/map/miniMapLogo.png" border="0" /></div>
<div id="searchbox">
<form>
Search for <input type="text" id="term" name="term" value="flannery-cars-greensburg"/> <input type="button" value="Search" onclick="return updateMap();"/>
<img id="spinner" src="images/spinner.gif" />
<span class="error" id="errorMessage" />
</form>
</div>
</div>
<div id="mapContainer"><div id="map"></div></div>
</body>
</html>
Website
http://www.724-streamline-marketing.com/testing2.html
I am trying to gather metrics for reviews, rating, map location from the yelp api, I am unsure why it will not stay.
Any help would be grateful or even point me in the right direction on using a 3rd party app to create yelp data
Your problem is simple,
<script src="http://maps.google.com/maps?file=api&v=2&key=[AIzaSyByEg0pBD4dGr3gZCk863XZZ0ZBkqhDhR4]"
Get rid of the brackets [] surrounding the key.
Related
I am working on a graph that shows the temperature, date and time. Until now everything is working pretty good, but in order to get the new values from my MySQL database in need to completely refresh my page.
I want to be able to update the graph without pressing the Refresh button.
This is the code:
<?php require($_SERVER['DOCUMENT_ROOT'] . '/assets/php/getTemp.php' ); ?>
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<title>RPi</title>
</head>
<style>
div.tooltip {
position: absolute;
text-align: center;
width: 120px;
height: 28px;
padding: 3px;
font: 12px sans-serif;
background: lightgrey;
border: 0px;
border-radius: 8px;
pointer-events: none;
}
body { font: 14px Arial;}
path {
stroke: #FF8C00;
stroke-width: 3;
fill: none;
}
.axis path,
.axis line {
fill: none;
stroke: black;
stroke-width: 2;
shape-rendering: crispEdges;
}
.grid .tick {
stroke: grey;
stroke-opacity: 0.3;
shape-rendering: geometricPrecision;
}
.grid path {
stroke-width: 0;
}
</style>
<body>
<div id="option">
<input name="updateButton"
type="button"
value="Update"
onclick="updateData()"
/>
</div>
<!-- load the d3.js library -->
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 30, right: 20, bottom: 30, left: 50},
width = 800 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
var parseDate = d3.time.format("%Y-%m-%d %H:%M:%S").parse;
var formatTime = d3.time.format("%d-%m-%Y %H:%M:%S");
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x)
.orient("bottom");
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
var valueline = d3.svg.line()
.interpolate("basis")
.x(function(d) { return x(d.datetime); })
.y(function(d) { return y(d.temperature); });
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
function make_x_axis() {
return d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(5)
}
function make_y_axis() {
return d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5)
}
<?php echo "data=".$json_data.";" ?>
data.forEach(function(d) {
d.datetime = parseDate(d.datetime);
d.temperature = +d.temperature;
});
x.domain(d3.extent(data, function(d) { return d.datetime; }));
y.domain([0, d3.max(data, function(d) { return d.temperature; })]);
svg.append("path")
.attr("class", "line")
.attr("d", valueline(data));
svg.selectAll("dot")
.data(data)
.enter().append("circle")
.attr("r", 4)
.attr("cx", function(d) { return x(d.datetime); })
.attr("cy", function(d) { return y(d.temperature); })
.on("mouseover", function(d) {
div.transition()
.duration(200)
.style("opacity", 1);
div.html(formatTime(d.datetime) + "<br/>" + d.temperature + " ℃")
.style("left", (d3.event.pageX + 16) + "px")
.style("top", (d3.event.pageY + 16) + "px")
.style("position", "absolute");
})
.on("mouseout", function(d) {
div.transition()
.duration(50)
.style("opacity", 0);
});
svg.append("g")
.attr("class", "grid")
.attr("transform", "translate(0," + height + ")")
.call(make_x_axis()
.tickSize(-height, 0, 0)
.tickFormat("")
)
svg.append("g")
.attr("class", "grid")
.call(make_y_axis()
.tickSize(-width, 0, 0)
.tickFormat("")
)
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
</script>
</body>
I tried to do this:
function updateData() {
//d3.json("/assets/php/getTemp.php", function(error, data) {
<?php echo "data=".$json_data.";" ?>
data.forEach(function(d) {
d3.select("body").selectAll("svg")
d.datetime = parseDate(d.datetime);
d.temperature = +d.temperature;
});
x.domain(d3.extent(data, function(d) { return d.datetime; }));
y.domain([0, d3.max(data, function(d) { return d.temperature; })]);
var svg = d3.select("body").transition();
svg.select(".line")
.duration(750)
.attr("d", valueline(data));
svg.select(".x.axis")
.duration(750)
.call(xAxis);
svg.select(".y.axis")
.duration(750)
.call(yAxis);
};
but nothing happens, not even an error.
If it matters this is the PHP code used to get the temperatures and time form MySQL:
<?php
$hostname = 'localhost';
$username = 'root';
$password = 'admin';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=temp_database",
$username, $password);
$sth = $dbh->prepare("
SELECT `datetime`, `temperature` FROM `tempLog`
");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$json_data = json_encode($result);
?>
What i need to do ?
Look into using the d3.json function. This lets you get json from php scripts without reloading the entire page from scratch. It's AJAX stuff, but the d3 helper functions hide the details.
https://github.com/mbostock/d3/wiki/Requests
PS. Remember, it will be an asynchronous call, so see the accepted answer here as well:
JSON output from PHP using d3.json
As to why it doesn't work currently, my hunch*, though there's not enough info to confirm, is that there's no change because it's always the same data, so nothing will change
<?php echo "data=".$json_data.";" ?>
That line^^^ in updateData is evaluated once at the start and then the whole function is plonked into the javascript realm. However many times you then call updateData, that previously generated javascript variable (data={some_json}) won't change without reloading the php page that generated updateData, even if you call that database related php that generates the server side variable.
*could be nonsense, but the bit above the line is still right
im trying to do the following with my current script:
Saving Google Geo Location Informations in File, when the Visitor clicks "Accept Detection of my location"
Output Google Maps URL with the Information
<!DOCTYPE html>
<html>
<head>
<style>
#tripmeter {
border: 0px double black;
padding: 0px;
margin: 0px 0;
}
p {
color: #222;
font: 14px Arial;
}
span {
color: #00C;
}
</style>
</head>
<body>
<div id="tripmeter">
<p>
Starting Location (lat, lon):<br/>
<span id="startLat">???</span>°, <span id="startLon">???</span>°
</p>
<p>
Current Location (lat, lon):<br/>
<span id="currentLat">???</span>°, <span id="currentLon">???</span>°
</p>
<p>
Distance from starting location:<br/>
<span id="distance">0</span> km
</p>
</div>
<script>
window.onload = function() {
var startPos;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
startPos = position;
document.getElementById("startLat").innerHTML = startPos.coords.latitude;
document.getElementById("startLon").innerHTML = startPos.coords.longitude;
}, function(error) {
alert("Error occurred. Error code: " + error.code);
// error.code can be:
// 0: unknown error
// 1: permission denied
// 2: position unavailable (error response from locaton provider)
// 3: timed out
});
navigator.geolocation.watchPosition(function(position) {
document.getElementById("currentLat").innerHTML = position.coords.latitude;
document.getElementById("currentLon").innerHTML = position.coords.longitude;
document.getElementById("distance").innerHTML =
calculateDistance(startPos.coords.latitude, startPos.coords.longitude,
position.coords.latitude, position.coords.longitude);
});
}
};
// Reused code - copyright Moveable Type Scripts - retrieved May 4, 2010.
// http://www.movable-type.co.uk/scripts/latlong.html
// Under Creative Commons License http://creativecommons.org/licenses/by/3.0/
function calculateDistance(lat1, lon1, lat2, lon2) {
var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d;
}
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
</script>
</body>
</html>
<meta charset="utf-8"/>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
</head>
<body>
<div id="pos" style="width:800px; height:600px;">
Detection Location..
</div>
<script>
function initialize(coords) {
var latlng = new google.maps.LatLng(coords.latitude, coords.longitude);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("pos"), myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "You"
});
}
navigator.geolocation.getCurrentPosition(function(position){
initialize(position.coords);
}, function(){
document.getElementById('pos').innerHTML = 'Failed to detect Location.';
});
</script>
<?php
$dns = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$ip = $_SERVER['REMOTE_ADDR'];
$rand2 = time();
$port= htmlspecialchars(
$_SERVER['REMOTE_PORT']);
$browser= htmlspecialchars(
$_SERVER['HTTP_USER_AGENT']);
$ausgabe="• I WANT TO SAVE THE GOOGLE MAPS URL WITH THE DETECTED LOCATION •";
$datum=date("d.m.Y, H:i:s");
$array = file("location.log"); // Datei in ein Array einlesen
array_unshift($array, "".$datum." ".$ausgabe."\n");
$string = implode("", $array);
file_put_contents("location.log", $string);
?>
</body>
</html>
Anyone has a good idea? :)
If you want to save the longitude and latitude into a file (please check the Google API terms of usage if you are even allowed to do that), you have to get the coordinates first, then send them to your server via AJAX.
The below examples are not "copy/paste" material, since I didn't try them out. Use them as a general guideline.
First, you need to create a script, that will get the coordinates:
<html>
<head>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<body>
<div id="pos" style="width:800px; height:600px;">
Detection Location..
</div>
<script>
$(function(){
function initialize(coords) {
$.ajax({
url: 'saveLocation.php',
data: {
longitude:coords.longitude,
latitude:coords.latitude
},
error: function() {
$('#pos').html("Could not save location");
},
success: function(data) {
$('#pos').html("Location saved successfully");
},
type: 'POST'
});
}
navigator.geolocation.getCurrentPosition(function(position){
initialize(position.coords);
}, function(){
$('#pos').html('Failed to detect Location.');
});
});
</script>
</body>
</html>
On your server, you need a PHP script ""saveLocation.php":
<?php
$ausgabe=$_POST['longitude'].":".$_POST['latitude'];
$datum=date("d.m.Y, H:i:s");
$array = file("location.log"); // Datei in ein Array einlesen
array_unshift($array, "".$datum." ".$ausgabe."\n");
$string = implode("", $array);
file_put_contents("location.log", $string);
echo json_encode(array("success"=>"true"));
?>
I used jQuery to simplify some of the regular stuff, like sending data via AJAX or changing the inner HTML of an element.
Again, this code is not in working condition. It will not work if you just copy/paste it
This question already has answers here:
Google Maps Api v3 - find nearest markers
(7 answers)
Closed 9 years ago.
I'm trying to create an application in php that displays several markers on google map and allow a user to get the nearest marker when he click anywhere on the map. I tried the following code. But its not working. Can anyone please help?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps Javascript API v3 Example: Loading clustered data from an XML</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=geometry&sensor=false"></script>
<style type="text/css">
html, body { height: 100%; }
</style>
<script type="text/javascript">
//<![CDATA[
var side_bar_html = "";
var gmarkers = [];
var map = null;
var markerclusterer = null;
function createMarker(latlng, name, html) {
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);
});
gmarkers.push(marker);
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
}
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
function initialize() {
var myOptions = {
zoom: 12,
center: new google.maps.LatLng(8.491118,76.949840),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
google.maps.event.addListener(map, 'click', find_closest_marker);
downloadUrl("marker.xml", function(doc) {
map.markers = [];
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i].getAttribute("Lat"));
var lng = parseFloat(markers[i].getAttribute("Longt"));
var point = new google.maps.LatLng(lat,lng);
var hname = markers[i].getAttribute("Hname");
var Phone = markers[i].getAttribute("Phone");
var html="<b>"+hname+"</b><br>"+Phone;
var marker = createMarker(point,hname+" "+Phone,html);
}
markerCluster = new MarkerClusterer(map, gmarkers);
document.getElementById("side_bar").innerHTML = side_bar_html;
});
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
function find_closest_marker( event ) {
var closestMarker = -1;
var closestDistance = Number.MAX_VALUE;
for( i=0;i<gmarkers.length; i++ ) {
var distance = google.maps.geometry.spherical.computeDistanceBetween(gmarkers[i].getPosition(),event.latLng);
if ( distance < closestDistance ) {
closestMarker = i;
closestDistance = distance;
}
}
map.setCenter(gmarkers[closestMarker].getPosition());
if (map.getZoom() < 16) map.setZoom(16);
google.maps.event.trigger(gmarkers[closestMarker], 'click');
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<table border="1">
<tr>
<td>
<div id="map_canvas" style="width: 550px; height: 450px"></div>
</td>
<td valign="top" >
<div id="side_bar" style="width:300px;height:450px; text-decoration: underline; color: #4444ff; overflow:auto;"></div>
</td>
</tr>
</table>
</body>
</html>
marker.xml
<markers>
<marker Hname="CHC Anchuthengu" Lat="8.6734310" Longt="76.7581770"/>
<marker Hname="PHC Perumathura" Lat="8.6218640" Longt="76.7975220"/>
<marker Hname="PHC Keezhattingal" Lat="8.6982130" Longt="76.7915000"/>
<marker Hname="PHC Azhoor" Lat="8.6408080" Longt="76.8252470"/>
</markers>
You need to create the map.markers array (this part not tested):
downloadUrl("phpsqlajax_genxml.php", function(data) {
map.markers = [];
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var hname = markers[i].getAttribute("Hname");
var Phone = markers[i].getAttribute("Phone");
var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("Lat")), parseFloat(markers[i].getAttribute("Longt")));
var html = "<b>" + hname + "<br/>" + Phone + "</b>";
var type = "bar";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
map.markers.push(marker);
bindInfoWindow(marker, map, infoWindow, html);
}
});
I would suggest using the geometry library computeDistanceBetween function
function find_closest_marker( event ) {
var closestMarker = -1;
var closestDistance = Number.MAX_VALUE;
for( i=0;i<map.markers.length; i++ ) {
var distance = google.maps.geometry.spherical.computeDistanceBetween(gmarkers[i].getPosition(),event.latLng);
if ( distance < closestDistance ) {
closestMarker = i;
closestDistance = distance;
}
}
allert(map.markers[closestMarker].title);
}
working example
I'm developing a mobile app that allows a user to record some data about their favourite monuments. Now, when a user takes a photo of their monument the lat and long values are instantly recorded. Giving me two separate values.
The user then syncs this data with my PostGreSQL database. I want to manipulate this data on my website service.
All I want is a simple map plugin which will take each (so like a foreach loop) record relating to a user (name of monument, lat and long) and display it on a map with icon markers.
So for example, you could have a favourite monument in Cardiff and one in London. You would have two markers displayed on your account map and when you click on their a pop-up says 'Cardiff Museum' and 'London Eye'.
I've tried multiple searches on Google but to no avail.
Has anyone ever implemented something similar? I'm good with either PHP or JQuery or both solutions!
Here is the code where you can pass multiple lat-long combinations to add a marker for each user location.
Repeat this code for every marker you need in your loop to traverse locations array.
t.push('Location Name 1');
x.push(33.84659); // you can write like x.push(<?php echo $userloc[0]['lat']?>)
y.push(-84.35686);
h.push('<p><strong>Location Name 1</strong><br/>Address 1</p>');
The complete code is given below.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() { initialize(); });
function initialize() {
var map_options = {
center: new google.maps.LatLng(33.84659,-84.35686),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var google_map = new google.maps.Map(document.getElementById("map_canvas"), map_options);
var info_window = new google.maps.InfoWindow({
content: 'loading'
});
var t = [];
var x = [];
var y = [];
var h = [];
t.push('Location Name 1');
x.push(33.84659);
y.push(-84.35686);
h.push('<p><strong>Location Name 1</strong><br/>Address 1</p>');
t.push('Location Name 2');
x.push(33.846253);
y.push(-84.362125);
h.push('<p><strong>Location Name 2</strong><br/>Address 2</p>');
var i = 0;
for ( item in t ) {
var m = new google.maps.Marker({
map: google_map,
animation: google.maps.Animation.DROP,
title: t[i],
position: new google.maps.LatLng(x[i],y[i]),
html: h[i]
});
google.maps.event.addListener(m, 'click', function() {
info_window.setContent(this.html);
info_window.open(google_map, this);
});
i++;
}
}
</script>
<div id="map_canvas" style="width:400px;height:400px;">Google Map</div>
This code may help you. You can see its working demo here(http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=-33.866603&lon=151.207108&setLatLon=Set)
<!-- Original script taken from: http://conversationswithmyself.com/googleMapDemo.html -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<style type="text/css">
<!--
h1 {
font-family:sans-serif;
color:blue;
text-align: center;
font-size:120%;
}
.tekst {
font-family:sans-serif;
color:blue;
font-size:100%;
}
.smalltekst {
font-family:sans-serif;
color:black;
font-size:80%;
}
-->
</style>
<style type="text/css">
v\:* {
behavior:url(#default#VML);
}
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAF4PVqw0p5l92pEmE39k0MRQWxhPw7-SAnMb84NfHs4vQ3HTp4BTb-yeL6fQg7Up9d9idBGy5naXydw" type="text/javascript"></script>
<title>Google Maps Latitude, Longitude Popup</title>
</head>
<body>
<h1>Google Maps Latitude, Longitude Popup</h1>
<div style="width: 600px;" class="tekst"><b>Simply click on the map on a location and it will provide you with the latitude and longitude in the callout window.</b></div>
<div id="map" style="width: 600px; height: 400px"></div>
<div id="geo" style="width: 300px;position: absolute;left: 620px;top: 100px;" class="tekst">
<form name="setLatLon" action="googleMapLocation.php">
<b>* Coordinates:</b><br />
<table>
<tr><td>* Lat:</td><td><input type='text' name='lat' id="frmLat"></td></tr>
<tr><td>* Lon:</td><td><input type='text' name='lon' id="frmLon"></td></tr>
</table>
<input type="submit" name="setLatLon" value="Set"><br />
</form><br />
<b>* Flickr tags:</b><br />
<textarea id="geocode" cols="30" rows="2"></textarea><br />
<br />
<b>* RoboGEO tags:</b><br />
<textarea id="geocodeRoboGEO" cols="30" rows="2"></textarea><br />
* Show location on Multimap<br />
* Permanent Link<br /><br />
<script type="text/javascript">
<!--
google_ad_client = "pub-1588116269263536";
google_alternate_color = "FFFFFF";
google_ad_width = 234;
google_ad_height = 60;
google_ad_format = "234x60_as";
google_ad_type = "text";
//2006-09-30: Map
google_ad_channel ="0993881556";
google_color_border = "DDDDDD";
google_color_bg = "DDDDDD";
google_color_link = "0000FF";
google_color_text = "333333";
google_color_url = "333333";
//-->
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
</div>
<div style="width: 600px;" class="smalltekst">
<p><i>Address lookup has been removed because it violated the ToS of Google Maps.</i></p>
Based on code taken from this website and this website.<br />
All other errors are caused by code written by Pierre Gorissen.<br />
</div>
<script type="text/javascript">
//<![CDATA[
var baseLink = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php";
var multimapBaseLink = "http://www.multimap.com/map/browse.cgi?scale=10000&icon=x";
var geocoder = new GClientGeocoder();
var setLat = 51.618017;
var setLon = 2.48291;
// argItems code taken from
// http://www.evolt.org/article/Javascript_to_Parse_URLs_in_the_Browser/17/14435/?format=print
function argItems (theArgName) {
sArgs = location.search.slice(1).split('&');
r = '';
for (var i = 0; i < sArgs.length; i++) {
if (sArgs[i].slice(0,sArgs[i].indexOf('=')) == theArgName) {
r = sArgs[i].slice(sArgs[i].indexOf('=')+1);
break;
}
}
return (r.length > 0 ? unescape(r).split(',') : '')
}
function getCoordForAddress(response) {
if (!response || response.Status.code != 200) {
alert("Sorry, we were unable to geocode that address\n\n Sorry, dat adres bestaat blijkbaar niet!");
} else {
place = response.Placemark[0];
setLat = place.Point.coordinates[1];
setLon = place.Point.coordinates[0];
setLat = setLat.toFixed(6);
setLon = setLon.toFixed(6);
document.getElementById("frmLat").value = setLat;
document.getElementById("frmLon").value = setLon;
}
placeMarker(setLat, setLon)
}
function placeMarker(setLat, setLon) {
var message = "geotagged geo:lat=" + setLat + " geo:lon=" + setLon + " ";
document.getElementById("geocode").value = message;
var messageRoboGEO = setLat + ";" + setLon + "";
document.getElementById("geocodeRoboGEO").value = messageRoboGEO;
document.getElementById("geocode").focus();
document.getElementById("geocode").select();
document.getElementById("maplink").href = baseLink + "?lat=" + setLat + "&lon=" + setLon ;
document.getElementById("multimap").href = multimapBaseLink + "&lat=" + setLat + "&lon=" + setLon ;
document.getElementById("frmLat").value = setLat;
document.getElementById("frmLon").value = setLon;
var map = new GMap(document.getElementById("map"));
map.addControl(new GSmallMapControl()); // added
map.addControl(new GMapTypeControl()); // added
map.centerAndZoom(new GPoint(setLon, setLat), 12);
var point = new GPoint(setLon, setLat);
var marker = new GMarker(point);
map.addOverlay(marker);
GEvent.addListener(map, 'click', function(overlay, point) {
if (overlay) {
map.removeOverlay(overlay);
} else if (point) {
map.recenterOrPanToLatLng(point);
var marker = new GMarker(point);
map.addOverlay(marker);
var matchll = /\(([-.\d]*), ([-.\d]*)/.exec( point );
if ( matchll ) {
var lat = parseFloat( matchll[1] );
var lon = parseFloat( matchll[2] );
lat = lat.toFixed(6);
lon = lon.toFixed(6);
var message = "geotagged geo:lat=" + lat + " geo:lon=" + lon + " ";
var messageRoboGEO = lat + ";" + lon + "";
} else {
var message = "<b>Error extracting info from</b>:" + point + "";
var messagRoboGEO = message;
}
marker.openInfoWindowHtml(message);
document.getElementById("geocode").value = message;
document.getElementById("geocodeRoboGEO").value = messageRoboGEO;
document.getElementById("geocode").focus();
document.getElementById("geocode").select();
document.getElementById("maplink").href = baseLink + "?lat=" + lat + "&lon=" + lon ;
document.getElementById("multimap").href = multimapBaseLink + "&lat=" + lat + "&lon=" + lon ;
document.getElementById("frmLat").value = lat;
document.getElementById("frmLon").value = lon;
}
});
}
function findAddress() {
myAddress = document.getElementById("address").value;
geocoder.getLocations(myAddress, getCoordForAddress);
}
if (argItems("lat") == '' || argItems("lon") == '') {
placeMarker(setLat, setLon);
} else {
var setLat = parseFloat( argItems("lat") );
var setLon = parseFloat( argItems("lon") );
setLat = setLat.toFixed(6);
setLon = setLon.toFixed(6);
placeMarker(setLat, setLon);
}
//]]>
</script>
<!-- Start twatch code -->
<script type="text/javascript"><!--
//<![CDATA[
document.write('<scr'+'ipt type="text/javascript" src="/Pierre/twatch/jslogger.php?ref='+( document["referrer"]==null?'':escape(document.referrer))+'&pg='+escape(window.location)+'&cparams=true"></scr'+'ipt>');
//]]>
//--></script>
<!-- End twatch code -->
</body>
</html>
I'd like to use google maps in an unconventional way. I want to execute the javacript but I do not want to render any images. Rather I want to send some data to a file, use some of the computational functions the API has to offer and then pass back a text response. I attempted this with the following code but I then realized this probably won't work as javascript is run in a browser and not as a remote web service. That being said, how could a remote server call a 'web service' much like the one my code below has to offer with the goal of getting the simple 'yes' or 'no' response.
<?php
// Get vars
$lat=$_GET["lat"];
$lon=$_GET["lon"];
?>
<!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="https://maps.googleapis.com/maps/api/js?key=MYKEYNOTYOURS:)&sensor=true&libraries=geometry">
</script>
<script type="text/javascript">
// Poygon getBounds extension - google-maps-extensions
// http://code.google.com/p/google-maps-extensions/source/browse/google.maps.Polygon.getBounds.js
if (!google.maps.Polygon.prototype.getBounds) {
google.maps.Polygon.prototype.getBounds = function(latLng) {
var bounds = new google.maps.LatLngBounds();
var paths = this.getPaths();
var path;
for (var p = 0; p < paths.getLength(); p++) {
path = paths.getAt(p);
for (var i = 0; i < path.getLength(); i++) {
bounds.extend(path.getAt(i));
}
}
return bounds;
}
}
// Polygon containsLatLng - method to determine if a latLng is within a polygon
google.maps.Polygon.prototype.containsLatLng = function(latLng) {
// Exclude points outside of bounds as there is no way they are in the poly
var bounds = this.getBounds();
if(bounds != null && !bounds.contains(latLng)) {
return false;
}
// Raycast point in polygon method
var inPoly = false;
var numPaths = this.getPaths().getLength();
for(var p = 0; p < numPaths; p++) {
var path = this.getPaths().getAt(p);
var numPoints = path.getLength();
var j = numPoints-1;
for(var i=0; i < numPoints; i++) {
var vertex1 = path.getAt(i);
var vertex2 = path.getAt(j);
if (vertex1.lng() < latLng.lng() && vertex2.lng() >= latLng.lng() || vertex2.lng() < latLng.lng() && vertex1.lng() >= latLng.lng()) {
if (vertex1.lat() + (latLng.lng() - vertex1.lng()) / (vertex2.lng() - vertex1.lng()) * (vertex2.lat() - vertex1.lat()) < latLng.lat()) {
inPoly = !inPoly;
}
}
j = i;
}
}
return inPoly;
}
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(38.990842,-76.93625),
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var box = [new google.maps.LatLng(38.9913160,-76.937079),
new google.maps.LatLng(38.991333,-76.936119),
new google.maps.LatLng(38.990287, -76.936108),
new google.maps.LatLng(38.990278,-76.937057),
new google.maps.LatLng(38.990495,-76.937052),
new google.maps.LatLng(38.990499,-76.936424),
new google.maps.LatLng(38.991091,-76.93643),
new google.maps.LatLng(38.991104,-76.937079)
];
var mPoint = [new google.maps.LatLng(38.991300,-76.936165)];
var AVpoly = new google.maps.Polygon({path:box,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2,
fillColor:"#0000FF",
fillOpacity:0.4});
var lat = <?php echo $lat; ?>;
var lon = <?php echo $lon; ?>;
if(AVpoly.containsLatLng(new google.maps.LatLng(lat,lon), box) == true) {
document.write("Yes");
}
else
{
document.write("No");
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
This is not allowed! You may only use Google Maps Data if you are displaying a map that is publicly accessible. See section 9.1 of the TOS and 10.1.1 (g) "No Use of Content without a Google Map.":