I create a square polygon by using the min and max values of the latitude and longitude of the furtherst points of my incoming data.
$poly = " $maxLng $maxLat , $minLng $maxLat , $minLng $minLat , $maxLng $minLat , $maxLng $maxLat ";
But this means that at least two markers are always the borders of this box. How can I push out the points and enlarge the overall size of the box by say 5% in all directions but I still need the lat/lon of each of those corners?
A small example of how to use the turfjs library and the transformScale method
const map = L.map('mapid').setView([52.308478623663355, 19.281005859375004], 6);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: '© OpenStreetMap contributors'
}).addTo(map);
const test = [
[54.80068486732236, 18.292236328125004],
[53.89786522246521, 14.611816406250002],
[51.055207338584964, 15.281982421875002],
[49.57510247172322, 19.138183593750004],
[50.57626025689928, 23.642578125000004],
[52.214338608258224, 23.148193359375004],
[52.86912972768522, 23.741455078125],
[54.29729354239267, 22.928466796875004],
[54.29729354239267, 19.489746093750004],
[54.80068486732236, 18.292236328125004]
];
L.polygon(test, {
color: 'red'
}).addTo(map);
var poly = turf.polygon([test]);
var scaledPoly = turf.transformScale(poly, 1.05);
const {
coordinates
} = scaledPoly.geometry;
L.polygon(coordinates, {
color: 'white'
}).addTo(map);
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
}
body {
min-height: 100%;
}
#mapid {
width: 100%;
height: 100%;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.6.0/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.6.0/dist/leaflet.js"></script>
<script src="https://cdn.jsdelivr.net/npm/#turf/turf#5/turf.min.js"></script>
<div id="mapid"></div>
Related
I have some questions and i hope someone help me to solve it . the questions is:
1) i want to save the drawing polygon into database mysql.
2) each polygon can have different name and insert into database.
3) edit and delete the polygon that was created and save it into database.
in my code i'm using google map tool to draw and give color to each polygon was drawing on google map. so i hope someone help me of code about save all these into database. Thank you
code.
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false&libraries=drawing"></script>
<style type="text/css">
#map, html, body {
padding: 0;
margin: 0;
height: 100%;
}
#panel {
width: 200px;
font-family: Arial, sans-serif;
font-size: 13px;
float: right;
margin: 10px;
}
#color-palette {
clear: both;
}
.color-button {
width: 14px;
height: 14px;
font-size: 0;
margin: 2px;
float: left;
cursor: pointer;
}
#delete-button {
margin-top: 5px;
}
</style>
<script type="text/javascript">
var drawingManager;
var selectedShape;
var colors = ['#1E90FF', '#FF1493', '#32CD32', '#FF8C00', '#4B0082'];
var selectedColor;
var colorButtons = {};
function clearSelection() {
if (selectedShape) {
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
selectedShape = shape;
shape.setEditable(true);
selectColor(shape.get('fillColor') || shape.get('strokeColor'));
}
function deleteSelectedShape() {
if (selectedShape) {
selectedShape.setMap(null);
}
}
function selectColor(color) {
selectedColor = color;
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
colorButtons[currColor].style.border = currColor == color ? '2px solid #789' : '2px solid #fff';
}
// Retrieves the current options from the drawing manager and replaces the
// stroke or fill color as appropriate.
var polylineOptions = drawingManager.get('polylineOptions');
polylineOptions.strokeColor = color;
drawingManager.set('polylineOptions', polylineOptions);
var rectangleOptions = drawingManager.get('rectangleOptions');
rectangleOptions.fillColor = color;
drawingManager.set('rectangleOptions', rectangleOptions);
var circleOptions = drawingManager.get('circleOptions');
circleOptions.fillColor = color;
drawingManager.set('circleOptions', circleOptions);
var polygonOptions = drawingManager.get('polygonOptions');
polygonOptions.fillColor = color;
drawingManager.set('polygonOptions', polygonOptions);
}
function setSelectedShapeColor(color) {
if (selectedShape) {
if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE) {
selectedShape.set('strokeColor', color);
} else {
selectedShape.set('fillColor', color);
}
}
}
function makeColorButton(color) {
var button = document.createElement('span');
button.className = 'color-button';
button.style.backgroundColor = color;
google.maps.event.addDomListener(button, 'click', function() {
selectColor(color);
setSelectedShapeColor(color);
});
return button;
}
function buildColorPalette() {
var colorPalette = document.getElementById('color-palette');
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
var colorButton = makeColorButton(currColor);
colorPalette.appendChild(colorButton);
colorButtons[currColor] = colorButton;
}
selectColor(colors[0]);
}
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(22.344, 114.048),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
});
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true
};
// Creates a drawing manager attached to the map that allows the user to draw
// markers, lines, and shapes.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
markerOptions: {
draggable: true
},
polylineOptions: {
editable: true
},
rectangleOptions: polyOptions,
circleOptions: polyOptions,
polygonOptions: polyOptions,
map: map
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
if (e.type != google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function() {
setSelection(newShape);
});
setSelection(newShape);
}
});
// Clear the current selection when the drawing mode is changed, or when the
// map is clicked.
google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
google.maps.event.addListener(map, 'click', clearSelection);
google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);
buildColorPalette();
}
google.maps.event.addDomListener(window, 'load', initialize);
Ok, considering the broad nature to the question and lack of supporting structure / resources you will need to study and adapt if the following does what you need.
The first step would be to create the database structure you need - here I have created two, very basic, mySQL tables in a new database called gm_polygons. I'm not suggesting that these schemas will be sufficient for all the data that you need to store in the tables - such as colour, stroke, title etc etc but will give a starting point.
create table `paths` (
`id` int(10) unsigned not null auto_increment,
`pid` int(10) unsigned not null default '0',
`lat` float not null default '0',
`lng` float not null default '0',
primary key (`id`),
index `pid` (`pid`)
)
collate='utf8_general_ci'
engine=innodb;
create table `polygon` (
`id` int(10) unsigned not null auto_increment,
`name` varchar(50) not null default '0',
primary key (`id`)
)
collate='utf8_general_ci'
engine=innodb;
The php map page. The map loads, in this case centred upon London, and assigns a listener to the map which allows drawing of the polygon ( only polygons in this demo, no circles or polylines etc ) - the form has an input for the name of the poly and a button to send, via ajax, the details to the php script to process.
You could, after generating the db and tables shown here, modify the following byadding relevant details for host,user,password etc and run this to test.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* process the addition of the polygon */
if( !empty( $_POST['name'] ) && !empty( $_POST['path'] ) ){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'gm_polygons';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$name=$_POST['name'];
$path=json_decode( $_POST['path'] );
/* insert new path */
$sql='insert into polygon set `name`=?';
$stmt=$db->prepare( $sql );
if( !$stmt )exit( 'Error: query 1' );
$stmt->bind_param('s',$name);
$stmt->execute();
$stmt->free_result();
$stmt->close();
/* get the ID for the newly inserted Polygon name */
$id=$db->insert_id;
/* add all the latlng pairs for the polygon */
$sql='insert into `paths` ( `pid`, `lat`, `lng` ) values ( ?, ?, ? )';
$stmt=$db->prepare( $sql );
if( !$stmt )exit( 'Error: query 2' );
$stmt->bind_param( 'idd', $id, $lat, $lng );
foreach( $path as $obj ){
$lat=$obj->lat;
$lng=$obj->lng;
$stmt->execute();
}
$stmt->close();
echo json_encode(
array(
'name'=>$name,
'points'=>count($path)
)
);
}
exit();
}
?>
<html>
<head>
<meta charset='utf-8' />
<title>Google Maps: Storing Polygons in database</title>
<script async defer src='//maps.google.com/maps/api/js?key=APIKEY-gFJ0&callback=initMap®ion=GB&language=en'></script>
<script>
let map;
let div;
let bttn;
let input;
let options;
let centre;
let poly;
let path;
let polypath;
function initMap(){
const ajax=function( url, params, callback ){
let xhr=new XMLHttpRequest();
xhr.onload=function(){
if( this.status==200 && this.readyState==4 )callback( this.response )
};
xhr.open( 'POST', url, true );
xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
xhr.send( buildparams( params ) );
};
const buildparams=function(p){
if( p && typeof( p )==='object' ){
p=Object.keys( p ).map(function( k ){
return typeof( p[ k ] )=='object' ? buildparams( p[ k ] ) : [ encodeURIComponent( k ), encodeURIComponent( p[ k ] ) ].join('=')
}).join('&');
}
return p;
};
const createpoly=function(){
poly=new google.maps.Polygon({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.35,
draggable:true,
editable:true
});
poly.setMap( map );
return poly;
};
centre=new google.maps.LatLng( 51.483719, -0.020037 );
div=document.getElementById('map');
input=document.querySelector('#container > form > input[name="polyname"]');
bttn=document.querySelector('#container > form > input[type="button"]');
options = {
zoom: 15,
center: centre,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: false,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
mapTypeIds: [ 'roadmap', 'terrain', 'satellite', 'hybrid' ]
}
};
map = new google.maps.Map( div, options );
createpoly();
google.maps.event.addListener( map, 'click', e=>{
path=poly.getPath();
path.push( e.latLng );
});
google.maps.event.addListener( poly, 'rightclick', e=>{
poly.setMap( null );
createpoly();
});
bttn.addEventListener('click',e=>{
if( input.value!='' ){
path=poly.getPath();
polypath=[];
for( let i=0; i < path.length; i++ ){
let point=path.getAt( i );
polypath.push( { lat:point.lat(), lng:point.lng() } )
}
let params={
path:JSON.stringify( polypath ),
name:input.value
}
let url=location.href;
let callback=function(r){
console.info( r );
input.value='';
poly.setMap( null );
createpoly();
};
/* send the polygon data */
ajax.call( this, url, params, callback );
}
})
}
</script>
<style>
body{ background:white; }
#container{
width: 90%;
min-height: 90vh;
height:auto;
box-sizing:border-box;
margin: auto;
float:none;
margin:1rem auto;
background:whitesmoke;
padding:1rem;
border:1px solid gray;
display:block;
}
#map {
width: 100%;
height: 80%;
clear:none;
display:block;
z-index:1!important;
background:white;
border:1px solid black;
}
</style>
</head>
<body>
<div id='container'>
<form method='post'>
<input type='text' name='polyname' />
<input type='button' value='Commit' title='Store the polygon' />
</form>
<div id='map'></div>
<div id='data'></div>
</div>
</body>
</html>
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
I am working on custom form builder for one of my clients where we have functionality like drag fields , resize, apply css like borders and align fields using jquery. i am done with dragging,resizing and css but one of the major requirement is to apply "google drawing red rule " as we have in google drawing.
i have attached a screencast video as well as screencast images to clarify what red rule is.
http://screencast.com/t/ow6s5zKt9P
http://screencast.com/t/e1SL26gFJT8v
http://screencast.com/t/QAJGB7PzEwB
http://screencast.com/t/OoM6BqAH
Video:
http://screencast.com/t/ORaqAVWX4XGu
As can be seen in the above screen casts when ever we drag/draw a field and overlap with other fields it highlights the vertical and horizontal center of the dragging field or the overlap field in Red color (hence the title red rule). it also highlights the borders of any field overlapping the other field or moving out of the canvas area. it also shows whether field can be inscribed inside in another field while dragging.
I am looking at some one who can guide me in correct direction to acchive this functionality. i need to apply this red rule effect other than drawing or any thing. please sugguest any possibilities.
Any help is greatly appreciated.
i got the solutuon.
you can check her http://jsfiddle.net/elin/A6CpP/
<div id="parent">
<div class="other-objects" style="left:0px;top:300px;background:#a00;"></div>
<div class="other-objects"></div>
<div class="other-objects" style="left:400px;top:20px;"></div>
<div class="objectx"></div>
<div class="objecty"></div>
</div>
$.ui.plugin.add("draggable", "smartguides", {
start: function(event, ui) {
var i = $(this).data("draggable"), o = i.options;
i.elements = [];
$(o.smartguides.constructor != String ? ( o.smartguides.items || ':data(draggable)' ) : o.smartguides).each(function() {
var $t = $(this); var $o = $t.offset();
if(this != i.element[0]) i.elements.push({
item: this,
width: $t.outerWidth(), height: $t.outerHeight(),
top: $o.top, left: $o.left
});
});
},
stop: function(event, ui) {
$(".objectx").css({"display":"none"});
$(".objecty").css({"display":"none"});
},
drag: function(event, ui) {
var inst = $(this).data("draggable"), o = inst.options;
var d = o.tolerance;
$(".objectx").css({"display":"none"});
$(".objecty").css({"display":"none"});
var x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height,
xc = (x1 + x2) / 2, yc = (y1 + y2) / 2;
for (var i = inst.elements.length - 1; i >= 0; i--){
var l = inst.elements[i].left, r = l + inst.elements[i].width,
t = inst.elements[i].top, b = t + inst.elements[i].height,
hc = (l + r) / 2, vc = (t + b) / 2;
var ls = Math.abs(l - x2) <= d;
var rs = Math.abs(r - x1) <= d;
var ts = Math.abs(t - y2) <= d;
var bs = Math.abs(b - y1) <= d;
var hs = Math.abs(hc - xc) <= d;
var vs = Math.abs(vc - yc) <= d;
if(ls) {
ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left;
$(".objectx").css({"left":l-d-4,"display":"block"});
}
if(rs) {
ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left;
$(".objectx").css({"left":r-d-4,"display":"block"});
}
if(ts) {
ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
$(".objecty").css({"top":t-d-4,"display":"block"});
}
if(bs) {
ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top;
$(".objecty").css({"top":b-d-4,"display":"block"});
}
if(hs) {
ui.position.left = inst._convertPositionTo("relative", { top: 0, left: hc - inst.helperProportions.width/2 }).left - inst.margins.left;
$(".objectx").css({"left":hc-d-4,"display":"block"});
}
if(vs) {
ui.position.top = inst._convertPositionTo("relative", { top: vc - inst.helperProportions.height/2, left: 0 }).top - inst.margins.top;
$(".objecty").css({"top":vc-d-4,"display":"block"});
}
};
}
});
$('.other-objects').draggable({
containment: 'parent',
smartguides:".other-objects",
tolerance:5
});
#parent{
width:600px;
height:500px;
border:1px solid #000;
position:relative;
}
.other-objects{
background:#aaa;
width:100px;
height:100px;
display:block;
position:relative;
left:140px;
top:50px;
}
.objectx{
display:none;
//background:#fff;
width:0px;
height:100%;
position:absolute;
top:0px;
left:10px;
border-left: 2px solid red;
}
.objecty{
display:none;
//background:#fff;
width:100%;
height:0px;
position:absolute;
top:10px;
left:0px;
border-bottom: 2px solid red;
}
<!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.
I'm stuck on a current issue when I'm trying to use the custom infobox with google API v3 PHP / SQL Database. I'm having the hardest time figuring out where I messed up, the div shows up blank instead of having a map. Any help would awesome!
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"></script>
<script type="text/javascript">
var customIcons = {
Clinic: {
icon: 'icon_2.png',
},
Secondary: {
icon: 'icon_1.png',
}
};
function initialize() {
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 13,
scrollwheel: false,
mapTypeId: 'roadmap'
});
downloadUrl("xml.php", function(data) {
function createMarker(markerXML) {
var name = markerXML.getAttribute("name"),
postid = markers [i].getAttribute("post_id"),
address = markers[i].getAttribute("address"),
phone = markers[i].getAttribute("phone"),
listtype = markers[i].getAttribute("type"),
monday = markers[i].getAttribute("monday"),
tuesday = markers[i].getAttribute("tuesday"),
wednesday = markers[i].getAttribute("wednesday"),
thursday = markers[i].getAttribute("thursday"),
friday = markers[i].getAttribute("friday"),
saturday = markers[i].getAttribute("saturday"),
sunday = markers[i].getAttribute("sunday"),
type = markers[i].getAttribute("type"),
point = new google.maps.LatLng(
lat = parseFloat(markerXML.getAttribute("lat")),
lng = parseFloat(markerXML.getAttribute("lng")),
icon = customIcons[type] || {},
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(lat, lng),
icon: icon.icon,
}),
boxText = document.createElement("div");
boxText.style.cssText = "border: 1px solid black; margin-top: 8px; background: yellow; padding: 5px;";
boxText.innerHTML = "<b>" + name + "</b> <br/> <i>" + listtype + "</i> <br/>" + address + "<br/>" + phone + "<br/>" + monday + tuesday + wednesday + thursday + friday + saturday + sunday;
var myOptions = {
content: boxText,
disableAutoPan: false,
maxWidth: 0,
pixelOffset: new google.maps.Size(-140, 0),
zIndex: null,
boxStyle: {
background: "url('tipbox.gif') no-repeat",
opacity: 0.75,
width: "280px"
},
closeBoxMargin: "10px 2px 2px 2px",
closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif",
infoBoxClearance: new google.maps.Size(1, 1),
isHidden: false,
pane: "floatPane",
enableEventPropagation: false
};
var infoBox = new InfoBox(myOptions);
google.maps.event.addListener(marker, 'click', function () {
infoBox.open(map, marker);
}
});
}
var xml = data.responseXML,
markers = xml.documentElement.getElementsByTagName("marker"),
numMarkers = markers.length;
for (var i = 0; i < numMarkers; i++) {
createMarker(markers[i]);
}
});
}
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() {}
</script>
<div id="map_canvas" style="width: 500px; height: 300px"></div>
Look at the javascript console and fix the errors you find there. Just commenting out dowloadUrl call should get you your map back.
You didn't provide a sample of your xml, but the second step (after fixing your javascript errors) would be to open the xml feed in your browser and see if it is valid (or you could run it through an xml validator)
This article (which it looks like you might have started with) also provides some debugging suggestions.
working version