How pass data from parent page to popup? - javascript

I have following code:
parent page:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<a href=# onclick='showMap()'>show map <a>
<div id="map-canvas"></div>
</body>
<script>
function showMap(){
window.open('map.html','map','width=600,height=400');
}
</script>
</html>
map.html:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Info windows</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Uluru (Ayers Rock)'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
As you can see I use hardcode values for map marker rendering:
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
Can I pass these values from parent page to popup?

Since you asked just how to pass from parent to pop up an option would be querystring parameters:
<a href=# onclick='showMap(-25.363882,131.044922)'>show map <a>
function showMap(lat,lng){
window.open('map.html?lat='+lat+'&lng ='+lng,'map','width=600,height=400');
}
Then in map.html collect those values and use..
Update: Collecting query string values can be done in a lot of ways see the options with a quick search
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var lat = getParameterByName('lat');
var lon = getParameterByName('lon');
taken from : https://stackoverflow.com/a/901144/306921
You can also take a look at: Get query string parameters with jQuery
I tested and its all working:
resulting index.html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<a href=# onclick='showMap(-25.363882,131.044922)'>show map <a>
<div id="map-canvas"></div>
</body>
<script>
function showMap(lat,lng){
window.open('map.html?lat='+lat+'&lng ='+lng,'map','width=600,height=400');
}
</script>
</html>
and the resulting map.html:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Info windows</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var lat = getParameterByName('lat');
var lon = getParameterByName('lon');
function initialize() {
var myLatlng = new google.maps.LatLng(lat, lon);
var mapOptions = {
zoom: 4,
center: myLatlng
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Uluru (Ayers Rock)'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>

QueryString is a good way. However based on your requirement, You can also store it in parent page and read via javascript.
Storing value in parent page using dom:
<input type="hidden" id="lat" value="...."/>
You can also google to find how to store the data with window object itself(e.g window.myVar='xxx') and reading it from pop-up.
Accessing value in pop-page opened via window.open
var lat =window.opener.getElementById("lat").value;//use window.parent if opened as iframe

Related

Google geocoder does not work

This is my index.html file - The part i'm having trouble with is getting the geocode function to work. The form and button show up but nothing happens when i press the button at all.
<!DOCTYPE html>
<html>
<head>
<title>First Google Map</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(43.696299,-79.346271);
var myOptions = {
zoom:13,
center: latlng,
mapTypeId: google.maps.MapTypeId.MAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder = new google.maps.Geocoder();
var myPlacesKML = new google.maps.KmlLayer('http://mristo.webatu.com/melissaristo/kml/torontodonvalley.kml?ver=1');
myPlacesKML.setMap(map);
function geocode() {
address = document.getElementById("address").value;
geocoder.geocode({
'address': address,
'partialmatch': true}, geocodeResult);
}
}
</script>
</head>
<body onload="initialize()">
<input type="text" id="address">
<input type="button" onclick="geocode();" value="Geocode it!"
}
</script>
<body onload="initialize()">
<div id="map_canvas" style="width:500px; height:400px"></div>
</body>
</html>
The form and button show up but the the button doesn't do anything when i click it.
Any ideas? I'm very new to this and pretty lost
This code has a lot of bugs in it. I fixed it up. It will place a marker at the address you input in the text box.
<!DOCTYPE html>
<html>
<head>
<title>First Google Map</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
function initialize() {
var latlng = new google.maps.LatLng(43.696299,-79.346271);
var myOptions = {
zoom:13,
center: latlng,
mapTypeId: google.maps.MapTypeId.MAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder = new google.maps.Geocoder();
var myPlacesKML = new google.maps.KmlLayer('http://mristo.webatu.com/melissaristo/kml/torontodonvalley.kml?ver=1');
myPlacesKML.setMap(map);
}
function geocode() {
address = document.getElementById("address").value;
geocoder.geocode({
'address': address,
'partialmatch': true}, geocodeResult);
}
function geocodeResult( results, status )
{if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
}
</script>
</head>
<body onload="initialize()">
<input type="text" id="address">
<input type="button" onclick="geocode();" value="Geocode it!">
<div id="map_canvas" style="width:500px; height:400px"></div>
</body>
</html>
Here are the bugs:
1. extra }
2. map variable was local, needed to be global.
3. missing function geocodeResult
4. extra body tag
5. missing closing > from input
6. move geocode() from inside initialize() to global.

JQuery JavaScript Error in Browser, Not Dreamweaver

I'm trying to create a webpage that takes a location via a text box, and plots all recent earthquakes near that location on Google Maps.
I'm using Dreamweaver to debug my code, and the webpage works perfectly when I use the built-in live webpage feature it includes.
However, when I open the saved file in a browser, all I get is an error "Geocode was not successful for the following reason: ERROR". This isn't exactly helpful for figuring out what the issue is, and I have very little experience with web languages and developing web sites.
Any help or insight you can lend me would be greatly appreciated.
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<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=XXXXXXXXXXXXXXXXXXXX&sensor=true">
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
function codeAddress()
{
var loc = document.getElementById('locText').value;
geocoder.geocode( { 'address': loc}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);
var north = results[0].geometry.location.lat() + 1;
var south = results[0].geometry.location.lat() - 1;
var east = results[0].geometry.location.lng() + 1;
var west = results[0].geometry.location.lng() - 1;
var url;
url = 'http://api.geonames.org/earthquakesJSON?north=' + north + '&south=' + south + '&east=' + east + '&west=' + west + '&username=jpcguy89';
$.ajax(url,function(quakes)
{
$.each(quakes.earthquakes, function(k, aQuake){
var contentString = '<div id="content">' + '<p><b>ID:</b> ' + aQuake.eqid + '</p>' + '<p><b>Magnitude:</b> ' + aQuake.magnitude + '<p><b>Date:</b> ' + aQuake.datetime + '<p><b>Depth:</b> ' + aQuake.depth + '</div>';
var infowindow = new google.maps.InfoWindow
({
content: contentString
});
var latLng = new google.maps.LatLng(aQuake.lat,aQuake.lng);
var marker = new google.maps.Marker
({
position: latLng,
map: map,
title: 'Earthquake (' + aQuake.eqid + ')'
});
google.maps.event.addListener(marker, 'click', function()
{
infowindow.open(map,marker);
});
});
});
}
else
{
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<br />
<br />
<div id="test"></div>
<br />
<br />
<form id="geonamesFetch">
City/Location: <input type="text" id="locText" />
<input type="submit" id="submit" onclick="codeAddress()" />
</form>
<div id="map-canvas"/>
<p> </p>
<p> </p>
</body>
</html>
http://jsfiddle.net/mZGL3/
You are binding the click handler in the HTML:
<input type="submit" id="submit" onclick="codeAddress()" />
Done this way, the JavaScript is executed, but then the form is immediately submitted. You need to prevent the form from submitting. Remove the click handler from the html:
<input type="submit" id="submit" />
And bind to the submit handler in your JavaScript so that you can prevent the form from submitting. Add this to your JavaScript:
$(function(){
$("#geonamesFetch").on("submit", function(e) {
e.preventDefault();
codeAddress();
});
});
Demo: jsfiddle.net/mZGL3/3/
Edit: The other problem you have is your call to $.ajax(). That method expects an object, but you are passing a function. You can either change your code to pass an object, setting the function you have now as the success property:
$.ajax(url, {
success: function(quakes) {
...
}
});
Or use $.get(), which accepts a function as the second argument:
$.get(url, function (quakes) {
...
});
Demo: jsfiddle.net/mZGL3/4/
You seem to be loading mixed protocol ressources.
And your jsFiddle seems to have a ressource missing (http://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXX&sensor=true)
Fix your code to access NON httpS .. and try again.
Seen on your jsFiddle :
> Timestamp: 9/30/2013 3:40:41 PM Error: ReferenceError: google is not
> defined Source File: fiddle.jshell.net/mZGL3/show Line: 93
I updated your fiddle here, with the ressource, now, the error is : {"error": "Please use POST request"}

How to get my markers to update on a Leaflet map?

I've created a map that grabs data from a JSON-source and puts a marker for all drivers inside that JSON-data. Problem is, I want these drivers position to update all the time. To do so, I've created a function that repeats itself every 3 seconds. This will cause duplicated drivers, how to I get my markers just to update its position, not creating another one? Code below, JSON-data doesn't work for now due to CORS.
Code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="generator" content=
"HTML Tidy for Linux/x86 (vers 25 March 2009), see www.w3.org" />
<title></title>
<meta charset="utf-8" />
<meta name="viewport" content=
"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.5/leaflet.css" type=
"text/css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js" type="text/javascript">
</script><!--[if lte IE 8]>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.5/leaflet.ie.css" />
<![endif]-->
<style type="text/css">
/*<![CDATA[*/
body {
padding: 0;
margin: 0;
}
html, body, #map {
height: 100%;
}
/*]]>*/
</style>
</head>
<body>
<div id="map"></div><script src="https://www.google.com/jsapi?.js" type=
"text/javascript">
</script><script src="http://cdn.leafletjs.com/leaflet-0.5/leaflet.js" type=
"text/javascript">
</script><script src="leaflet-ajax.js" type="text/javascript">
</script><script type="text/javascript">
//<![CDATA[
init(); //Calls the "grab my location" function
function init() {
var map = L.map('map', {
center: [51.505, -0.09],
zoom: 13
}),
marker = L.marker(map.getCenter()).addTo(map)
.bindPopup("<center><b>Jag<\/b><\/center>").openPopup();
glcl = google.loader.ClientLocation,
onLocationfound = function (e) {
marker.setLatLng(e.latlng);
map.setView(marker.getLatLng(), map.getZoom());
};
L.tileLayer('http://{s}.tile.cloudmade.com/1fa9625d371549a298938509a2eac256/997/256/{z}/{x}/{y}.png').addTo(map);
map.on('locationfound', onLocationfound);
if (glcl) { //when google.loader.ClientLocation contains result
onLocationfound({
latlng: [glcl.latitude, glcl.longitude]
});
} else {}
map.locate();
driversRealtime();
function driversRealtime() {
setInterval(function () {
var url = "data.json";
var name;
var img;
$.getJSON(url,
function (response) {
name = response.drivers[0].name;
img = response.drivers[0].img;
for (var i = 0; i < response.drivers.length; i++) {
var driver = response.drivers[i];
var m = L.marker(new L.LatLng(driver.currentLat, driver.currentLon)).addTo(map)
.bindPopup("<center><b>" + driver.name + "<\/b><\/center>");
}
});
}, 3000); //Delay i millisekunder
}
}
// API-URL: http://blackcab.didair.se/api/drivers
//]]>
</script>
</body>
</html>

How do I set javascript variables or call functions with the razor syntax?

This is a beginners question about web programming. Basically I have a page that shows a default address using the Google Map API. It works fine looking up "221B Baker Street, London, United Kingdom", but there is a textbox that I would like to be able to write an address in and then look it up. It's an cshtml-page and I know of the razor syntax
#{if(IsPost) { do something }}
So basically I would like to take the Request.Form["FindAddress"]; from the textbox and and set it to the javascript myAddress variable so that the users address will be shown instead. But I don't know how to do it inline coding. It keeps giving me syntax errors when placing the IsPost-condition inside the -tag for the javascript functions. Here is the complete page
<!DOCTYPE html>
<html>
<head id="head">
<title></title>
<link href="#Server.MapPath("~/Styles/Site.css")" rel="stylesheet" type="text/css" />
</head>
<script src="http://maps.google.com/maps?file=api&v=2&key=<YOUR_API_KEY>&sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
var myAddress = "221B Baker Street, London, United Kingdom"; // how do I overwrite this if it is (isPost)?
var map;
var geocoder;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(51.5, -0.1), 10);
map.setUIToDefault();
geocoder = new GClientGeocoder();
showAddress(myAddress);
}
}
function showAddress(address) {
geocoder.getLatLng(address, function (point) { if (!point) { alert(address + " not found"); } else { map.setCenter(point, 15); var marker = new GMarker(point); map.addOverlay(marker); marker.openInfoWindow(address); } });
}
</script>
<body onload="initialize()" onunload="GUnload()">
<form id="form1" runat="server">
<div>
<input type="text" id="FindAddress" name="FindAddress" />
</div>
<div id="map" style="width: 500px; height: 500px"></div>
</form>
</body>
</html>
I haven't tried the below code, but I hope it will work. Basically I've put the conditional checking logic outside the script block and store the result in a variable and that is referenced in the javascript.
#{
var address = "221B Baker Street, London, United Kingdom";
if (Request.HttpMethod == "POST")
{
address = Request.Form["FindAddress"];
}
}
<script type="text/javascript">
var myAddress = "#address"; // how do I overwrite this if it is (isPost)?
var map;
var geocoder;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(51.5, -0.1), 10);
map.setUIToDefault();
geocoder = new GClientGeocoder();
showAddress(myAddress);
}
}
function showAddress(address) {
geocoder.getLatLng(address, function (point) { if (!point) { alert(address + " not found"); } else { map.setCenter(point, 15); var marker = new GMarker(point); map.addOverlay(marker); marker.openInfoWindow(address); } });
}
</script>

problem in javascript

I am using the following code ,here I am showing addresses of
properties.xml with markers on google map. It gives me no error but also displaying nothing on google map.
Can anybody tell me where is the problem in my code?
properties.xml file:
<properties>
<property>
<type>apartment</type>
<address>538 Little Lonsdale Street,Melbourne,VIC </address>
</property>
<property>
<type>apartment</type>
<address>196 Little Lonsdale Street,Melbourne,VIC</address>
</property>
<property>
<type>apartment</type>
<address>5/5 Close Ave,Dandenong,VIC </address>
</property>
</properties>
html file:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>property</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAB1CHU9LrppxpqwUwaxkvTBRIez7zTAJDrX7CdEV86wzEyVzTHBQKDxL9qiopaHZkOJ8F2t0RQW9W8A"
type="text/javascript"></script>
<script type="text/javascript" src="map.js"></script>
</head>
<body onload="load()" onunload="GUnload()">
<div id="map" style="width: 500px; height: 400px"></div>
</body>
</html>
map.js file:
var map;
var geocoder;
var xml;
var property;
var address;
function load()
{
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(-24.994167,134.866944), 4);
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
geocoder = new GClientGeocoder();
GDownloadUrl("../../data/properties.xml", function(data) {
xml = GXml.parse(data);
property = xml.documentElement.getElementsByTagName("property");
for (var i = 0; i < property.length; i++) {
address = property[i].getElementsByTagName("address");
address = address.firstChild.nodeValue;
geocoder.getLocations(address, addToMap);}
});
}
function addToMap(response)
{
place = response.Placemark[0];
point = new GLatLng(place.Point.coordinates[1],
place.Point.coordinates[0]);
marker = new GMarker(point);
map.addOverlay(marker);
}
I tried your code and got the maps displaying on first load but there was a JS error. It was this particular line:
address = address.firstChild.nodeValue;
Should be this to get the text inside <address>:
address = address[0].childNodes[0].nodeValue;
Here is a portion of the map when it worked:
Just to mention that I couldn't see any markers at first so I replaced:
map.setCenter(new GLatLng(37.997022, -122.6), 11);
with:
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
Not sure if that's what you're expecting but that's how it turned out.
*UPDATE*
To create a marker you can use this function
function createMarker(point, address)
{
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
map.openInfoWindowHtml(point, address);
});
return marker;
}
Apply the createMarker to map.addOverlay:
map.addOverlay(createMarker(point, response.name));

Categories

Resources