I'm fairly new at this. I'm trying to build a store locator and trying to figure out how to pass an input value from one page to another page. User would input their zipcode or address in a form on one page and the map and locations would be called on another page using the input.
I'm using ehound store locator platform (sample - here -> http://www.ehoundplatform.com/api/1....nd-google.html)
The map/locator script is this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Store Locator Demo using FreeHound and Google Maps V.3</title>
<style type="text/css">
#map_canvas {
height: 400px;
width:710px;
margin-bottom: 10px;
}
.addressBox {
margin-bottom:10px;
}
</style>
<script type="text/javascript" src="http://www.ehoundplatform.com/api/1.0 /proximity.js?key=xz396aw1qe432q1"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false®ion=AU"></script>
<script type="text/javascript">
var geocoder;
var map;
var bounds;
var markersArray = [];
var infoWindow;
var mapCenterLat = '-28.1594';
var mapCenterLon = '135.6456';
function initialize() {
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 4,
center: new google.maps.LatLng(mapCenterLat, mapCenterLon),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//initialise single info window to show only one at a time
infoWindow = new google.maps.InfoWindow();
//improve usability by centering map around search point on zoom in/out
google.maps.event.addListener(map, 'zoom_changed', function() { if(mapCenterLat && mapCenterLon) {
setTimeout('centerMap(mapCenterLat, mapCenterLon)', 300);
}
});
}
function addMarkerOverlay(location, title, infoBox, image) {
var marker = new google.maps.Marker({
position: location,
map: map,
icon: image
});
marker.setTitle(title);
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(infoBox);
infoWindow.open(map, marker);
});
markersArray.push(marker);
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
function searchAroundMe() {
deleteOverlays();
bounds = new google.maps.LatLngBounds();
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
//custom marker to mark initial search location
var image = new google.maps.MarkerImage('search_location.png',
// This marker is 32 pixels wide by 32 pixels tall.
new google.maps.Size(32, 32),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is the center of the red circle at 16,16.
new google.maps.Point(16, 16)
);
addMarkerOverlay(results[0].geometry.location, 'search spot', 'search initiated from here', image);
bounds.extend(results[0].geometry.location);
var searchLatitude = results[0].geometry.location.lat();
var searchLongitude = results[0].geometry.location.lng();
mapCenterLat = searchLatitude;
mapCenterLon = searchLongitude;
freeHound = new FreeHound( 'showLocs' );
search = new FH_Search();
search.count = 10; //number of locations to be returned in the result set
search.max_distance = 0; //distance limit for proximity search in km, 0 for unlimited
//search from a specific point using latitude and longitude of that point
search.point = new FH_Location( new FH_LatLon( searchLatitude,searchLongitude ) );
//search.filters = new Array();
//search.filters.push( new FH_SearchFilter('cat_id', 'eq', '177') );
search.create_log = false;
freeHound.proximitySearch( search );
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function showLocs(response){
if ( response.error_code ) {
alert(response.error_message);
}
if ( response.record_set ) {
//show results in a table
var resultsTable = '<table border="1" cellspacing="0" cellpadding="3" summary="">';
resultsTable += '<tr>';
resultsTable += '<td>#<\/td>';
resultsTable += '<td>Street Address<\/td>';
resultsTable += '<td>Town/Suburb/City<\/td>';
resultsTable += '<td>Postal Code<\/td>';
resultsTable += '<td>State/Province<\/td>';
resultsTable += '<td>Distance<\/td>';
resultsTable += '<td>Longitude<\/td>';
resultsTable += '<td>Latitude<\/td>';
resultsTable += '<\/tr>';
for (var record_count = 0, rl = response.record_set.length; record_count < rl; record_count++ ) {
var record = response.record_set[record_count];
var title = record.details.location_name;
var infoBoxContent = '<strong>Location #'+(record_count+1).toString()+'<\/strong>';
infoBoxContent += '<br \/>'+record.address.street_address+'<br \/>'+record.address.town + ', ' + record.address.postal_code +'<br \/>';
infoBoxContent += 'Distance: '+record.distance.km+'km<br \/>';
addMarkerOverlay(new google.maps.LatLng(record.latitude, record.longitude), title, infoBoxContent, null);
if (record_count < 6) {
bounds.extend(new google.maps.LatLng(record.latitude, record.longitude));
}
resultsTable += '<tr>';
resultsTable += '<td>'+(record_count+1).toString()+'<\/td>';
resultsTable += '<td>'+record.address.street_address+'<\/td>';
resultsTable += '<td>'+record.address.town+'<\/td>';
resultsTable += '<td>'+record.address.postal_code+'<\/td>';
resultsTable += '<td>'+record.address.state+'<\/td>';
resultsTable += '<td>'+record.distance.km+'KM<\/td>';
resultsTable += '<td>'+record.longitude+'<\/td>';
resultsTable += '<td>'+record.latitude+'<\/td>';
resultsTable += '<\/tr>';
}
map.fitBounds(bounds);
resultsTable += '<\/table>';
var resultSet = document.getElementById('resultSet');
resultSet.innerHTML = resultsTable;
}
}
function centerMap(lat,lon) {
var centrePoint = new google.maps.LatLng(lat,lon);
map.setCenter(centrePoint);
}
</script>
</head>
<body onload="initialize()">
<div class="addressBox">
<form action="" onsubmit="searchAroundMe(); return false;">
<input id="address" type="textbox" value="">
<input type="submit" name="search" value="Address Search">
</form>
</div>
<div id="map_canvas"></div>
<div id="resultSet"></div>
</body>
</html>
and the form itself would be on another page. Trying to pull the address input over. This obviously doesn't work
<!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>KOI Store Locator</title>
</head>
<body>
<div>
<form action="ehound.php" method="post">
<input id="address" name="address" type="textbox">
<input type="submit" name="search" value="Address Search">
</form>
</div>
</body>
</html>
I've looked around on passing inputs via php and such, but this script seems to call on javascript as well and I'm having trouble implementing anything that works. Any help would be greatly appreciated.
Attach a click handler to your form submission button, in the handler simply get the values needed from your form, build a query string with the needed parameters, and window.location.assign("yourotherpage.html?"+theQueryString). Then just pull the query string parameters in the javascript on the other page.
I am not sure what ehound is but in general there are 2 good ways to do this.
You just submitted a form which sends data to the server, so just have the server insert the data you need into the next page.
The specifics of how to accomplish this would be mostly dependant on what server you are using.
Or a non server approach:
store a cookie and then if the other page is on the same domain then you should be able to retrieve it.
Cookies are easy, http://www.quirksmode.org/js/cookies.html (you can skip the long and mildly confusing explanation about the specifics of cookies and just grab the script).
Another way you could pass the information around is in a hidden form element. This qustion is pretty similar and has some good advice.
Related
With My Code I deserialized Json object for a city includes Tourist places. Each Tourist Places there are Name, Shor-Text, GeoCo-ordinates and Image. IN my controller class I deserialize all of this object and put all of this data in ViewBag.Now this portion is ok So far. My code to get The name and json deserilization in Controller class is as follows-
public ActionResult Index(City objCityModel)
{
string name = objCityModel.Name;
return View();
}
public ActionResult GoogleMap(City objCityModel)
{
string name = objCityModel.Name;
ViewBag.Title = name;
var ReadJson = System.IO.File.ReadAllText(Server.MapPath(#"~/App_Data/POI_Json/" + name + ".json"));
RootObject json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<RootObject>(ReadJson);
List<Poi> mycities = new List<Poi>();
foreach (var item in json.poi)
{
Poi obj = new Poi()
{
Name = item.Name,
Shorttext = item.Shorttext,
GeoCoordinates = item.GeoCoordinates,
Images = item.Images,
};
mycities.Add(obj);
}
ViewBag.Cities = mycities;
return View();
}
I create a search box to get the name to go to the google map view. I am giving this code just for understanding-
#using (Html.BeginForm("GoogleMap", "Home"))
{
<div class="wrapper wrapper-content">
#Html.TextBoxFor(m => m.Name)
<label for="somevalue">City Name</label>
<div class="input-group-btn">
<button id="mapViewBtn" class="btn btn-primary" type="submit">Map View</button>
}
</div>
</div>
}
Now My problem is in the GoogleMap view. I am getting how to use all of my View bag data in this google map. I use the below link to write my code. Well I am trying in my way but could no succeed. I only want to use Javascript not the Ajax. But This is not working at all. My code is as follows-
Modified Code
<meta name="viewport" content="width=device-width" />
<title>GoogleMap</title>
<script src="http://maps.google.com/maps/api/js?sensor=true" type="text/javascript"></script>
<style>
#map_canvas img{max-width:none}
</style>
<style>
.infoDiv {
height: 200px;
width: 300px;
-webkit-user-select: none;
background-color: white;
}
</style>
<div id="map_canvas" style="height: 600px;"></div>
#section scripts {
<section class="scripts">
<script type="text/javascript">
$(document).ready(function () {
Initialize();
});
function Initialize() {
google.maps.visualRefresh = true;
var #ViewBag.Title = new google.maps.LatLng(53.408841, -2.981397);
var mapOptions = {
zoom: 14,
center: Liverpool,
mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var myLatlng = new google.maps.LatLng(53.40091, -2.994464);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Tate Gallery'
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')
var cities = JSON.parse('#Html.Raw(Json.Encode(ViewBag.Cities))');
$.each(cities , function(index, obj){
var marker = new google.maps.Marker({
'position': new google.maps.LatLng(item.GeoLong, item.GeoLat),
'map': map,
'title':obj.Name
});
var infowindow = new google.maps.InfoWindow({
content: "<div class='infoDiv'><h2>" +
item.Name + "</h2>" + "<div><h4>Opening hours: " +
item.ShortText + "</h4></div></div>"
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
})
}
</script>
</section>
}
Convert ViewBag which contains list of poi into json array using #Html.Raw and Json.Encode and then loop thru the array using.
<script>
var cities = JSON.parse('#Html.Raw(Json.Encode(ViewBag.Cities))');
$.each(cities , function(index, obj){
//here obj contains the POI information
console.log(obj.GeoCoordinates);
});
</script>
First convert your c# object to Json like below.
Write this in your cshtml page on top
#{
var jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.Cities);
}
Then inside your script block you can do this.
<script>
var citiesList= JSON.parse(#Html.Raw(Json.Encode(jsonData)));
alert(citiesList);
</script>
let me know if you have any issues
I'm using for first time the DirectionsManager to create routes in Bing Maps AJAX v7. The route is created correctly, but comes with two small "infoboxes" showing "A" at the start of the route, and "B" at the final. I want to remove those infoboxes, but honestly, after reading all the documentation (http://msdn.microsoft.com/en-us/library/hh312832.aspx) and "Binging/Googling" a while, I can't found anything helpful. Also, I tried every option inside setRenderOptions. Any ideas?
directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
directionsManager.resetDirections();
directionsManager.setRenderOptions({autoDisplayDisambiguation: false,
autoUpdateMapView: true, displayManeuverIcons: false, displayPreItineraryItemHints: false, displayPostItineraryItemHints: false, displayRouteSelector: false, displayStepWarnings: false, drivingPolylineOptions: { strokeColor: new Microsoft.Maps.Color(150, 255, 51, 51), strokeThickness: 8 }
});
directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.driving });
var seattleWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: '000 fake street, Houston TX 77000' });
directionsManager.addWaypoint(seattleWaypoint);
var tacomaWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: '111 fake street, Houston TX 77111' });
directionsManager.addWaypoint(tacomaWaypoint);
directionsManager.calculateDirections();
One possible solution is to customize the pushpin to display blank pushpin with a small size (I've tried with another pushpin with 15x15 pixels size):
// Set the render options
directionsManager.setRenderOptions({
itineraryContainer: document.getElementById('itineraryDiv'),
displayWalkingWarning: false,
walkingPolylineOptions:{strokeColor: new Microsoft.Maps.Color(200, 0, 255, 0)},
waypointPushpinOptions: {icon:'pin_blank.png', height:1, width:1}
});
The other way might consist in calling the service by yourself and handling the request and response in your code. Here is an example: http://msdn.microsoft.com/en-us/library/gg427607.aspx
Here is the code that might be what you will help you:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript">
var map = null;
function GetMap()
{
// Initialize the map
map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Your Bing Maps Key", mapTypeId: Microsoft.Maps.MapTypeId.road });
}
function ClickRoute(credentials)
{
map.getCredentials(MakeRouteRequest);
}
function MakeRouteRequest(credentials)
{
var routeRequest = "http://dev.virtualearth.net/REST/v1/Routes?wp.0=" + document.getElementById('txtStart').value + "&wp.1=" + document.getElementById('txtEnd').value + "&routePathOutput=Points&output=json&jsonp=RouteCallback&key=" + credentials;
CallRestService(routeRequest);
}
function RouteCallback(result) {
if (result &&
result.resourceSets &&
result.resourceSets.length > 0 &&
result.resourceSets[0].resources &&
result.resourceSets[0].resources.length > 0) {
// Set the map view
var bbox = result.resourceSets[0].resources[0].bbox;
var viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(bbox[0], bbox[1]), new Microsoft.Maps.Location(bbox[2], bbox[3]));
map.setView({ bounds: viewBoundaries});
// Draw the route
var routeline = result.resourceSets[0].resources[0].routePath.line;
var routepoints = new Array();
for (var i = 0; i < routeline.coordinates.length; i++) {
routepoints[i]=new Microsoft.Maps.Location(routeline.coordinates[i][0], routeline.coordinates[i][1]);
}
// Draw the route on the map
var routeshape = new Microsoft.Maps.Polyline(routepoints, {strokeColor:new Microsoft.Maps.Color(200,0,0,200)});
map.entities.push(routeshape);
}
}
function CallRestService(request)
{
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", request);
document.body.appendChild(script);
}
</script>
</head>
<body onload="GetMap();">
<div id='mapDiv' style="position:relative; width:400px; height:400px;"></div>
<input id="txtStart" type="text" value="Seattle"/>
<input id="txtEnd" type="text" value="Portland"/>
<input type="button" value="Calculate Route" onclick="ClickRoute()"/>
</body>
</html>
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"}
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>
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));