I am having trouble parsing XML data in the JS code following it. I have several XML row tags that I am trying to pull data from, this is just a sample. There is a problem with the loop section in the JS code (I've never been good at loops) and I am only getting the information from the first row tag repeatedly in my sidebar. How do I get it to read all of the row tags?
<rows>
<row>
<time>2014-11-05T10:53:35.757Z</time>
<latitude>41.896</latitude>
<longitude>-119.6168</longitude>
<depth>1.6069</depth>
<mag>2.87</mag>
<magType>ml</magType>
<nst>4</nst>
<gap>145.83</gap>
<dmin>0.511</dmin>
<rms>0.1222</rms>
<net>nn</net>
<id>nn00466295</id>
<updated>2014-11-05T11:48:11.391Z</updated>
<place>68km ESE of Lakeview, Oregon</place>
<type>earthquake</type>
</row>
<row>
<time>2014-11-05T10:30:37.000Z</time>
<latitude>60.366</latitude>
<longitude>-151.8877</longitude>
<depth>70</depth>
<mag>2.5</mag>
<magType>ml</magType>
<nst/>
<gap/>
<dmin/>
<rms/>
<net>ak</net>
<id>ak11434200</id>
<updated>2014-11-05T11:53:47.658Z</updated>
<place>32km W of Cohoe, Alaska</place>
<type>earthquake</type>
</row>
.
.
.
</rows>
<!DOCTYPE html>
<html>
<head>
<title>Final Project</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100% }
#title { font-size: 30px }
.side_table { height:515px; overflow:auto; }
</style>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?"></script>
<script type="text/javascript" src="downloadxml.js"></script>
<script type="text/javascript">
var infoWindow = new google.maps.InfoWindow();
var markers = [];
function myclick(num) {
google.maps.event.trigger(markers[num], "click");
}
function createMarker(point,info,map) {
var iconURL = 'cone.png'; var iconSize = new google.maps.Size(20,34);
var iconOrigin = new google.maps.Point(0,0); var iconAnchor = new google.maps.Point(10,34);
var myIcon = {
url: iconURL,
size: iconSize,
origin: iconOrigin,
anchor: iconAnchor
};
var iconShape = [8,33, 4,15, 1,15, 0,12, 0,5, 6,0, 12,0, 19,14, 15,15, 10,33];
var myMarkerShape = {
coord: iconShape,
type: 'poly'
};
var myMarkerOpts = {
position: point,
map: map,
icon: myIcon,
shape: myMarkerShape
};
var marker = new google.maps.Marker(myMarkerOpts);
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infoWindow.close();
infoWindow.setContent(info);
infoWindow.open(map,marker);
});
}
function initialize() {
var latlng = new google.maps.LatLng(0, 0);
var mapOpts = {
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOpts);
downloadUrl("csv2xml.php", function(data) {
var xmlDoc = xmlParse(data);
var records = xmlDoc.getElementsByTagName("row");
var side_html = '<div class="side_table"> \
<table style="border-collapse: collapse" border="1" \
cellpadding="5"> \
<thead> \
<tr style="background-color:#e0e0e0"> \
<th>Location</th> \
<th>Magnitude</th> \
</tr> \
</thead> \
<tbody>';
for (var i = 0; i < records.length; i++) {
var rec = records[i];
var time = records[0].getElementsByTagName("time")[0].childNodes[0].nodeValue;
var lat = parseFloat(records[0].getElementsByTagName("latitude")[0].childNodes[0].nodeValue);
var lng = parseFloat(records[0].getElementsByTagName("longitude")[0].childNodes[0].nodeValue);
var depth = records[0].getElementsByTagName("depth")[0].childNodes[0].nodeValue;
var mag = records[0].getElementsByTagName("mag")[0].childNodes[0].nodeValue;
var id = records[0].getElementsByTagName("id")[0].childNodes[0].nodeValue;
var updated = records[0].getElementsByTagName("updated")[0].childNodes[0].nodeValue;
var place = records[0].getElementsByTagName("place")[0].childNodes[0].nodeValue;
var row = new google.maps.LatLng(lat, lng);
//Infowindow parameters
var html = "<strong>Location: </strong>" + place + "<br />" +
"<strong>Magnitude: </strong>" + mag + "<br />" +
"<strong>Depth: </strong>" + depth + "<br />" +
"<strong>Time: </strong>" + time + "<br />";
//Sidebar parameters
side_html += '<tr> \
<td>' + place + '</td> \
<td>' + mag + '</td> \
</tr>';
createMarker(row,html,map);
}
side_html += '</tbody> \
</table>';
document.getElementById("side_bar").innerHTML = side_html;
});
}
</script>
</head>
<body onload="initialize()">
<div id="title" style="position:absolute; left:10px; top:5px;"><b>RealTime Earthquakes Greater Than 2.5 Magnitude Over The Last Day</b></div>
<div id="map_canvas" style="width: 1000px; height: 500px; position: absolute; left: 10px; top: 40px"></div>
<div id="side_bar" style="width: 200px; height 500px; position: absolute; left: 1030px; top: 40px"></div>
<div id="notes" style="position:absolute; left:10px; top:550px; width:95%">
<u>Final Project Reflection</u><br>
<p></p>
</div>
</body>
</html>
Related
i am trying to display google map in website. i don't want to use embed method so, used this using async defer method.
Strange thing is my code works fine in when in html file but, when i use it in wordpress i get TypeError: $ is not a function error.
How come no type error in html file and typeError when i used in wordpress?
<script>
var rating;
var address;
var name;
var infoWindow = null;
function initMap() {
var map = new google.maps.Map(document.getElementById('mapDiv'), {
center: {lat: 33.531495, lng: -88.42207},
zoom: 19
});
var infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: 'ChIJJdJXNmjphogRo-W21kkhbJg'
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
rating = place.rating;
name = place.name;
//var labelIndex = 50;
address = "<div>" + place.formatted_address + "</div>"
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
});
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
place.formatted_address + '</div>');
infowindow.open(map, marker);
google.maps.event.addListener(map, 'idle', function(e) {
// Prevents card from being added more than once (i.e. when page is resized and google maps re-renders)
if ( $( ".place-card" ).length === 0 ) {
$(".gm-style").append('<div style="position: absolute; left: 0px; top: 34px;"> <div style="margin: 10px; padding: 1px; -webkit-box-shadow: rgba(0, 0, 0, 0.298039) 0px 1px 4px -1px; box-shadow: rgba(0, 0, 0, 0.298039) 0px 1px 4px -1px; border-radius: 2px; background-color: white;"> <div> <div class="place-card place-card-large"> <div class="place-desc-large"> <div class="place-name"></div><div class="image-place"><img id="photoLocation" src="" style="position: static; top: 0px;left: 0px;width: 175px;height: 165px;"></div><div class="address"></div></div><div class="navigate"> <div class="navigate"> <a class="navigate-link" href="https://www.google.com/maps/dir//33.53151,-88.422063/#33.53151,-88.422063,18z" target="_blank"> <div class="icon navigate-icon"></div><div class="navigate-text"> Directions </div></a> </div></div><div class="review-box"> <div id="review-number" class="review-number"></div>Reviews </div><div class="saved-from-source-link" style="display:none"> </div><div class="maps-links-box-exp"> <div class="time-to-location-info-exp" style="display:none"> <span class="drive-icon-exp experiment-icon"></span><a class="time-to-location-text-exp" style="display:none" target="_blank"></a><a class="time-to-location-text-exp" style="display:none" target="_blank"></a> </div><div class="google-maps-link"> View larger map </div></div></div></div>');
//$(".review-number").append(rating);
$("#review-number").append(rating);
fillCard(place);
//function to resize the map, responsive.
google.maps.event.addDomListener(window, 'resize', function() {
var center = googleMap.getCenter();
google.maps.event.trigger(googleMap, "resize");
googleMap.setCenter(center);
});
}
});
}
});
function fillCard(place){
var photos = place.photos;
var countRatig = rating.toString().slice(0,1);
$(".address").append(address);
$(".place-name").append(name);
$("#photoLocation").attr("src", photos[1].getUrl({'maxWidth': 175, 'maxHeight': 138}))
for (var i=0; i<countRatig; ++i ){
$("#review-number:nth-child(1)").append('<div class="icon rating-star rating-full-star"></div>');
}
}
}
</script>
Try to use jQuery instead of $ because wordpress use jQuery.noConflict() mode if I good remember.
Example:
if ( jQuery( ".place-card" ).length === 0 ) { ...
Change every $ symbol into jQuery
$ is not supported by wordpress
Better put the whole function in a document ready function. So the scripts executes after the page has been loaded. And you're able to keep the $ sign like so:
jQuery(document).ready(function( $ ) {
// Your function goes here...
if ( $( ".place-card" ).length === 0 ) {
//...
}
});
I'm using the Google Maps API, working in JavaScript/HTML. I'm trying to add simple buttons. If the user presses these buttons, it will turn left, turn right, etc on the map. However, my function changeHeading is being called, but not executing after it's called. What is the problem?
<head>
<meta charset="utf-8">
<title>Street View Add Third Panel</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
float: left;
height: 50%;
width: 50%;
}
#pano {
width: 100%;
height: 50%;
}
#floating-panel {
float: right;
width: 50%;
height: 50%;
}
</style>
</head>
<body>
<div id="map"></div>
<div id="floating-panel">
<table>
<tr>
<td><b>Position</b></td><td id="position-cell"> </td>
</tr>
<tr>
<td><b>POV Heading</b></td><td id="heading-cell">270</td>
</tr>
<tr>
<td><b>POV Pitch</b></td><td id="pitch-cell">0.0</td>
</tr>
<tr>
<td><b>Pano ID</b></td><td id="pano-cell"> </td>
</tr>
<tr>
<input type="button" value="Turn Left" onclick="changeHeading(-5);">
</tr>
<tr>
<input type="button" value="Turn Right" onclick="changeHeading(-5);">
</tr>
<tr>
<input type="button" value="Go Forward" onclick="changeHeading(-5);">
</tr>
<tr>
<input type="button" value="Go Backward" onclick="changeHeading(-5);">
</tr>
<table id="links_table"></table>
</table></div>
<div id="pano"></div>
<script>
function initialize() {
var fenway = {lat: 42.345573, lng: -71.098326};
var map = new google.maps.Map(document.getElementById('map'), {
center: fenway,
zoom: 14
});
var panorama = new google.maps.StreetViewPanorama(
document.getElementById('pano'), {
position: fenway,
pov: {
heading: 34,
pitch: 10
}
});
map.setStreetView(panorama);
panorama.addListener('pano_changed', function() {
var panoCell = document.getElementById('pano-cell');
panoCell.innerHTML = panorama.getPano();
});
panorama.addListener('links_changed', function() {
var linksTable = document.getElementById('links_table');
while (linksTable.hasChildNodes()) {
linksTable.removeChild(linksTable.lastChild);
}
var links = panorama.getLinks();
for (var i in links) {
var row = document.createElement('tr');
linksTable.appendChild(row);
var labelCell = document.createElement('td');
labelCell.innerHTML = '<b>Link: ' + i + '</b>';
var valueCell = document.createElement('td');
valueCell.innerHTML = links[i].description;
linksTable.appendChild(labelCell);
linksTable.appendChild(valueCell);
}
});
panorama.addListener('position_changed', function() {
var positionCell = document.getElementById('position-cell');
positionCell.firstChild.nodeValue = panorama.getPosition() + '';
});
panorama.addListener('pov_changed', function() {
var headingCell = document.getElementById('heading-cell');
var pitchCell = document.getElementById('pitch-cell');
headingCell.firstChild.nodeValue = panorama.getPov().heading + '';
pitchCell.firstChild.nodeValue = panorama.getPov().pitch + '';
});
}
function changeHeading( delta ) {
heading = panorama.getPov().heading;
panorama.setPov({ heading: heading + delta });
}
Panorama is a local variable and not available to changeHeading() function.
Do two things:
Define var panorama = null; outside the functions as a global variable.
Remove var from "var panorama = new google.maps.StreetViewPanorama(..." so it does not create a new local variable and use the global one instead.
Two problems:
panorama is a local variable, so is not accessible in the button onclick function (which runs in the global scope). You can fix that by using the google.maps.event.addDomListener function in the scope that it is defined in.
When you set the POV you need to set it with a POV object (otherwise you will get javascript errors InvalidValueError: setPov: in property pitch: not a number)
(inside initMap):
google.maps.event.addDomListener(document.getElementById("left"),'click', function() {changeHeading(-5)});
google.maps.event.addDomListener(document.getElementById("right"),'click', function() {changeHeading(5)});
function changeHeading(delta) {
var heading = panorama.getPov().heading;
var POV = panorama.getPov();
POV.heading = heading + delta;
panorama.setPov(POV);
}
proof of concept fiddle
code snippet:
function initialize() {
var fenway = {
lat: 42.345573,
lng: -71.098326
};
var map = new google.maps.Map(document.getElementById('map'), {
center: fenway,
zoom: 14
});
var panorama = new google.maps.StreetViewPanorama(
document.getElementById('pano'), {
position: fenway,
pov: {
heading: 34,
pitch: 10
}
});
map.setStreetView(panorama);
panorama.addListener('pano_changed', function() {
var panoCell = document.getElementById('pano-cell');
panoCell.innerHTML = panorama.getPano();
});
panorama.addListener('links_changed', function() {
var linksTable = document.getElementById('links_table');
while (linksTable.hasChildNodes()) {
linksTable.removeChild(linksTable.lastChild);
}
var links = panorama.getLinks();
for (var i in links) {
var row = document.createElement('tr');
linksTable.appendChild(row);
var labelCell = document.createElement('td');
labelCell.innerHTML = '<b>Link: ' + i + '</b>';
var valueCell = document.createElement('td');
valueCell.innerHTML = links[i].description;
linksTable.appendChild(labelCell);
linksTable.appendChild(valueCell);
}
});
panorama.addListener('position_changed', function() {
var positionCell = document.getElementById('position-cell');
positionCell.firstChild.nodeValue = panorama.getPosition() + '';
});
panorama.addListener('pov_changed', function() {
var headingCell = document.getElementById('heading-cell');
var pitchCell = document.getElementById('pitch-cell');
headingCell.firstChild.nodeValue = panorama.getPov().heading + '';
pitchCell.firstChild.nodeValue = panorama.getPov().pitch + '';
});
google.maps.event.addDomListener(document.getElementById("left"), 'click', function() {
changeHeading(-5)
});
google.maps.event.addDomListener(document.getElementById("right"), 'click', function() {
changeHeading(5)
});
function changeHeading(delta) {
var heading = panorama.getPov().heading;
var POV = panorama.getPov();
POV.heading = heading + delta;
panorama.setPov(POV);
}
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
float: left;
height: 50%;
width: 50%;
}
#pano {
width: 100%;
height: 50%;
}
#floating-panel {
float: right;
width: 50%;
height: 50%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map"></div>
<div id="floating-panel">
<table>
<tr>
<td><b>Position</b></td>
<td id="position-cell"> </td>
</tr>
<tr>
<td><b>POV Heading</b></td>
<td id="heading-cell">270</td>
</tr>
<tr>
<td><b>POV Pitch</b></td>
<td id="pitch-cell">0.0</td>
</tr>
<tr>
<td><b>Pano ID</b></td>
<td id="pano-cell"> </td>
</tr>
<tr>
<input type="button" id="left" value="Turn Left" onclick="changeHeading(-5);">
</tr>
<tr>
<input type="button" id="right" value="Turn Right" onclick="changeHeading(5);">
</tr>
<table id="links_table"></table>
</table>
</div>
<div id="pano"></div>
I have a semi-functional trip planner here:
http://roadtripsharing.com/plan-a-road-trip-js/
Source code:
<!DOCTYPE html>
<html>
<head>
<style>
#right-panel {
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
#right-panel select, #right-panel input {
font-size: 15px;
}
#right-panel select {
width: 100%;
}
#right-panel i {
font-size: 12px;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
float: left;
width: 70%;
height: 100%;
}
#right-panel {
margin: 20px;
border-width: 2px;
width: 20%;
float: left;
text-align: left;
padding-top: 20px;
}
#directions-panel {
margin-top: 20px;
background-color: #FFEE77;
padding: 10px;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=places"></script>
<div id="map"></div>
<div id="right-panel">
<div>
<b>Start:</b>
<input id="start" placeholder="Where to begin?" onFocus="geolocate()" type="text" />
<br>
<b>Waypoints:</b>
<br>
<ul style="list-style-type:none; padding: 0; margin: 0;" id="waypoints">
</ul>
<button id="newAutocomplete">Add One</button>
<input type="submit" id="addplace" value="Add One!">
<br>
<b>End:</b>
<br>
<input id="end" placeholder="Where to end?" onFocus="geolocate()" type="text" />
<br>
<input type="submit" id="submit" value="Plan It!">
</div>
<div id="directions-panel"></div>
</div>
<script>
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {
lat: 39.6,
lng: -106.5
}
});
directionsDisplay.setMap(map);
var start = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */
(document.getElementById('start')), {
types: ['geocode']
});
var end = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */
(document.getElementById('end')), {
types: ['geocode']
});
document.getElementById('addplace').addEventListener('click', function() {
addplace();
});
document.getElementById('submit').addEventListener('click', function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
}
var totalAC = 0;
$(document).on('click', "#waypoints input[type=text]",function () {
var currentInp = $(this).attr("id");
var placeBox = new google.maps.places.Autocomplete(document.getElementById(currentInp));
});
$("#newAutocomplete").click(function(){
totalAC = $("#waypoints input").length;
totalAC = totalAC + 1;
var codeVar = "<li><input id='place" + totalAC + "' placeholder='Come visit!' type='text' /></li>";
$("#waypoints").append(codeVar);
});
<!--
var j=0;
function addplace () {
var node = document.createElement("li"); // Create a <li> node
var textnode = document.createTextNode("<b>Waypoint</b>"); // Create a text node
node.appendChild(textnode); // Append the text to <li>
document.getElementById("waypoints").appendChild(node);
}
-->
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
waypts.push({
location: checkboxArray[i].value,
stopover: true
});
}
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions-panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment +
'</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
} else {
window.alert('Error! Do your dots connect?');
}
});
}
google.maps.event.addDomListener(window, 'load', initMap);
</script>
</body>
</html>
The first "Add One" button is a button and the second one is an input. I was using the input to add list items but the autocomplete didn't work and i got the advice in this question to add the jQuery you see working for the button click.
When I comment out the "Add One!" input the "Plan It!" input stops working. If you know why that would be, thank you in advance.
My main issue is that the trip planner is not taking the waypoints and including them in the route. The code should be taking each item from #waypoints and pushing it into waypts array to allow Google to do the routing. But only start and end points are included when user submits the "Plan It!" input. How to make the waypoints be included in the route?
If there is a way to add the list items with an input rather than a button for consistency with my other inputs and a way to do it without jquery that would be great as i am learning javascript and finding jquery a little confusing though it seems to be working other than not populating #waypoints with items in a way that can be pushed to waypts. Thanks.
Here are few changes you need to make in your JS, I already did for you-
var waypts = [];
function addplace() {
var inps = $('#waypoints input[type=text]');
for (var i = 1; i <= inps.length; i++) {
var a = $('#waypoints input[type=text]#place'+i);
waypts.push({
location: a.val(),
stopover: true
});
}
}
check this-
http://codepen.io/himanshuapril1/pen/RaQLgv
I have so far created a template of what i want and have manged to start getting each area to work, still got some work to do but I am currently trying to embed a KML file as a layer for my google map.
Here is my full coding below.
<!DOCTYPE html>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var markers = [];
function createMarker(latlng, html, map, refnum) {
var latlngtxt = (latlng.lat() + ',' + latlng.lng()).split(',');
$.each(latlngtxt, function(i, v){
v = Math.round(v);
v += v > 0? (i? 'E' : 'N') : (i? 'W' : 'S');
latlngtxt[i] = v.replace(/^-/, '');
});
latlngtxt = latlngtxt.join(', ');
var ref = $.trim($('#reference').val());
//ref = ref? ref + '<br>' : '';
var infowindow = new google.maps.InfoWindow({
content: ref || html //+ '#' + (markers.length + 1) + '<br>' + html + '<br>' + latlngtxt
});
var marker = new google.maps.Marker({
map: map,
position: latlng,
html: html,
infowindow: infowindow
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
$('#supplementwindow').html(infowindow.content).fadeIn();
});
marker.addListener('mouseout', function() {
infowindow.close();
$('#supplementwindow').fadeOut();
});
markers.push(marker);
}
var up206b = {};
var map;
function trace(message) {
if (typeof console != 'undefined') {
console.log(message);
}
}
up206b.initialize = function() {
var latlng = new google.maps.LatLng(52.136436, -0.460739);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
up206b.geocode();
}
var ctaLayer = new google.maps.KmlLayer({
url: 'file:///C|/wamp/www/maps/UK County border lines.kml',
map: map
});
var geocoder = new google.maps.Geocoder();
var bounds = new google.maps.LatLngBounds();
up206b.geocode = function() {
/* for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = []; */
var addresses = [$('#address').val(), $('#address2').val()];
addresses.forEach(function(address, refnum) {
if (address) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
createMarker(results[0].geometry.location, address, map, refnum);
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
});
}
jQuery(function($){
$('#removemarker').click(function(){
var tm = $('#themarkers'), si = tm.get(0).options.selectedIndex, $o = $('option', tm).eq(si), i = $o.val();
if(!i){return;}
$.each(markers, function(idx, v){
if(v.html === i){
v.setMap(null);
markers.splice(idx, 1);
return false;
}
});
$o.remove();
bounds = new google.maps.LatLngBounds();
if(markers.length){
$.each(markers, function(i, v){
bounds.extend(v.position);
});
map.fitBounds(bounds);
}
if(markers.length < 2){
map.setZoom(markers.length? 13 : 8);
}
});
$('#themarkers').change(function(){
this.title = this.options[this.options.selectedIndex].title;
var i = this.value;
if(!i){return;}
$.each(markers, function(idx, v){
if(v.html === i){
map.setCenter(v.position);
map.setZoom(10);
return false;
}
});
});
$('#showall').click(function(){
$('#themarkers').get(0).selectedIndex = 0;
if(!markers.length){
map.setCenter(new google.maps.LatLng(52.136436, -0.460739));
map.setZoom(13);
return;
}
map.fitBounds(bounds);
if(markers.length === 1){
map.setZoom(13);
}
});
});
</script>
</head>
<body onload="up206b.initialize()">
<div style="width:300px; height: 500px; float:right; padding-left:10px; padding-right:10px; margin: 50px 90px 50px 75px">
<h1 align="center">Map Search</h1>
<div style="border:1px solid #ccc; background:#e5e5e5; padding:10px;" align="center" >
<form >
<br>
Location 1 <input type="text" id="address">
<br>
<br>
Location 2
<input type="text" id="address2">
<br>
<br>
Reference
<input type="text" id="reference">
<br>
<br>
<input type="button" value="Submit" onClick="up206b.geocode()">
</form>
</div>
<div id="menu" style=" position: absolute; margin: 45px 89px;" >
<select id="Counties">
<option value="">Select County</option>
<option value="bedfordshire">Bedfordshire</option>
<option value="buckinghamshire">Buckinghamshire</option>
<option value="cambridgeshire">Cambridgeshire</option>
<option value="hertfordshire">Hertfordshire</option>
<option value="northamptonshire">Northamptonshire</option>
</select>
</div>
</div>
<div id="map_canvas" style="height: 500px; width: 500px; float:right; margin:20px 75px;"></div>
<div id="supplementwindow" style="border:1px solid #ccc; background:#e5e5e5; align-content:center; float:left; position:absolute; margin:200px 0px 200px 200px; padding: 5px; border-radius: 12px;" >
<input type="button" value="Assign">
</div>
<div id="menu2" style="position: absolute; right: 200px; top: 450px; border: 1px solid #bbb; padding: 5px;
border-radius: 12px;"><select id="themarkers"><option value="">Select Marker</option>
</select><br>
<input type="button" id="showall" title="Or Reset if None" value="Show All"><br>
<input type="button" id="removemarker" value="Remove Marker"></div>
</body>
</html>
The snippet of my code below is where I am trying to embed the KML file as a layer. I have tried using an online server URL with my KML and it doesn't work and also using Wamp as a local host server. Would it actually work with Wamp?
Have I placed to coding in the wrong place, have I written it wrong or missed out something? If anyone could give me some guidance, I would appreciate it thanks.
var ctaLayer = new google.maps.KmlLayer({
url: 'file:///C|/wamp/www/maps/UK County border lines.kml',
map: map
});
According to the documentation, the KmlLayer URL must be publicly accessible.
Overview
The Google Maps JavaScript API supports the KML and GeoRSS data formats for displaying geographic information. These data formats are displayed on a map using a KmlLayer object, whose constructor takes the URL of a publicly accessible KML or GeoRSS file.
proof of concept fiddle
code snippet:
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var kmlLayer = new google.maps.KmlLayer({
map: map,
url: "http://www.geocodezip.com/geoxml3_test/final_map_original_wales1c.xml"
})
google.maps.event.addListener(kmlLayer, 'status_changed', function() {
document.getElementById('status').innerHTML = "KmlStatus=" + kmlLayer.getStatus();
})
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="status"></div>
<div id="map_canvas"></div>
I have This Map I am working on and it opens at San Francisco. I would like to change this to open at a specified town, country of my choice. (i.e. London, England or Javea, Spain) The location changes on every page of my site and the "Town & Country" are inserted in the page from a database.
Example: {$listing_city} = Town {$listing_country} = Country
The search box at the top is not needed as I want to show the local restaurants, bars, doctors in that area. However, the search box can stay I just want the map to open in the respective town.
I am new hear and wondered if anyone can help.
Thanks in advance
Mal
<!DOCTYPE html>
<html>
<head>
<title>Google Developers</title>
<link rel="stylesheet" type="text/css" href="/_static/css/screen.css" />
<link rel="stylesheet" href="//www.google.com/cse/style/look/default.css" type="text/css" />
<link href='//fonts.googleapis.com/css?family=Open+Sans:300,400' rel='stylesheet' type='text/css'>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script id="jqueryui" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js" defer async></script>
<script src="//www.google.com/jsapi?key=AIzaSyCrlr1LScCevQ1epeHArLVww0eHlB6o1wg"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body class="docs framebox_body">
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var map, places, iw;
var markers = [];
var autocomplete;
function initialize() {
var myLatlng = new google.maps.LatLng(37.783259, -122.402708);
var myOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
places = new google.maps.places.PlacesService(map);
google.maps.event.addListener(map, 'tilesloaded', tilesLoaded);
autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'));
google.maps.event.addListener(autocomplete, 'place_changed', function() {
showSelectedPlace();
});
}
function tilesLoaded() {
google.maps.event.clearListeners(map, 'tilesloaded');
google.maps.event.addListener(map, 'zoom_changed', search);
google.maps.event.addListener(map, 'dragend', search);
search();
}
function showSelectedPlace() {
clearResults();
clearMarkers();
var place = autocomplete.getPlace();
map.panTo(place.geometry.location);
markers[0] = new google.maps.Marker({
position: place.geometry.location,
map: map
});
iw = new google.maps.InfoWindow({
content: getIWContent(place)
});
iw.open(map, markers[0]);
}
function search() {
var type;
for (var i = 0; i < document.controls.type.length; i++) {
if (document.controls.type[i].checked) {
type = document.controls.type[i].value;
}
}
autocomplete.setBounds(map.getBounds());
var search = {
bounds: map.getBounds()
};
if (type != 'establishment') {
search.types = [type];
}
places.search(search, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
clearResults();
clearMarkers();
for (var i = 0; i < results.length; i++) {
markers[i] = new google.maps.Marker({
position: results[i].geometry.location,
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(markers[i], 'click', getDetails(results[i], i));
setTimeout(dropMarker(i), i * 100);
addResult(results[i], i);
}
}
});
}
function clearMarkers() {
for (var i = 0; i < markers.length; i++) {
if (markers[i]) {
markers[i].setMap(null);
markers[i] == null;
}
}
}
function dropMarker(i) {
return function() {
markers[i].setMap(map);
}
}
function addResult(result, i) {
var results = document.getElementById('results');
var tr = document.createElement('tr');
tr.style.backgroundColor = (i% 2 == 0 ? '#F0F0F0' : '#FFFFFF');
tr.onclick = function() {
google.maps.event.trigger(markers[i], 'click');
};
var iconTd = document.createElement('td');
var nameTd = document.createElement('td');
var icon = document.createElement('img');
icon.src = result.icon.replace('http:', '');
icon.setAttribute('class', 'placeIcon');
var name = document.createTextNode(result.name);
iconTd.appendChild(icon);
nameTd.appendChild(name);
tr.appendChild(iconTd);
tr.appendChild(nameTd);
results.appendChild(tr);
}
function clearResults() {
var results = document.getElementById('results');
while (results.childNodes[0]) {
results.removeChild(results.childNodes[0]);
}
}
function getDetails(result, i) {
return function() {
places.getDetails({
reference: result.reference
}, showInfoWindow(i));
}
}
function showInfoWindow(i) {
return function(place, status) {
if (iw) {
iw.close();
iw = null;
}
if (status == google.maps.places.PlacesServiceStatus.OK) {
iw = new google.maps.InfoWindow({
content: getIWContent(place)
});
iw.open(map, markers[i]);
}
}
}
function getIWContent(place) {
var content = '<table style="border:0"><tr><td style="border:0;">';
content += '<img class="placeIcon" src="' + place.icon + '"></td>';
content += '<td style="border:0;"><b>' + place.name + '</b>';
content += '</td></tr></table>';
return content;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style type="text/css">
html, body {
margin: 0;
padding: 0;
height: 100%;
font-family: arial;
font-size: 13px;
overflow: hidden;
}
#map_canvas {
float: left;
width: 420px;
height: 406px;
}
#listing {
float: left;
margin-left: 1px;
width: 210px;
height: 406px;
overflow: auto;
cursor: pointer;
}
#controls {
padding: 5px;
}
.placeIcon {
width: 16px;
height: 16px;
margin: 2px;
}
#results {
border-collapse: collapse;
width: 184px;
}
#locationField {
margin-left: 1px;
}
#autocomplete {
width: 516px;
border: 1px solid #ccc;
}
</style>
<div id="locationField">
<input id="autocomplete" type="text">
</div>
<div id="map_canvas"></div>
<div id="listing">
<div id="controls">
<form name="controls">
<!--<input type="radio" name="type" value="establishment" onclick="search()" checked="checked"/>All<br/>-->
<input type="radio" name="type" value="restaurant" onclick="search()" />Restaurants<br/>
<input type="radio" name="type" value="police" onclick="search()" />Police Station<br/>
<input type="radio" name="type" value="church" onclick="search()" />Churches<br/>
<input type="radio" name="type" value="doctor" onclick="search()" />Doctor<br/>
<input type="radio" name="type" value="bar" onclick="search()" />Bars<br/>
<input type="radio" name="type" value="bank" onclick="search()" />Banks<br/>
</form>
</div>
<table id="results"></table>
</div>
</body>
</html>
You have to know latitude of towns you want. Than on every page you need to change this lines in initialize() function from
var myLatlng = new google.maps.LatLng(37.783259, -122.402708);
to
var myLatlng = new google.maps.LatLng(changeTHIS, andTHIS);
here is example for London
var myLatlng = new google.maps.LatLng(51.507222, -0.1275);