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));
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 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
i try to show a googlemaps map in my mvc4 partial view. It worked if i hardcode the latitude and longitude in the javascript - but i want to make it more dynamically. So i tried to replace the long and lat with variables. But i only got a grey googlemaps view. Here is my code. What is wrong? Can anyone help me to fix this?
<br />
<div id="map_canvas" style="width: 640px; height: 480px;">
</div>
#{
var lat = 6.9167;
var lng = 79.8473;
}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<script type="text/javascript">
$(document).ready(function () {
initialize();
});
function initialize() {
var mapOptions = {
center: new google.maps.LatLng('#lat', '#lng'),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
</script>
Try with:
<br />
<div id="map_canvas" style="width: 640px; height: 480px;">
</div>
#{
var lat = "6.9167";
var lng = "79.8473";
}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<script type="text/javascript">
$(document).ready(function () {
initialize();
});
function initialize(lat, lng) {
var mapOptions = {
center: new google.maps.LatLng(#lat, #lng),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
</script>
Edited
If latitude and longitude values are stored as double into variables or properties, you should pay attention to the string convertion because of the culture format problem.
I think that the best solution is to use the ToString("0.#####", CultureInfo.CreateSpecificCulture("en-GB")) method, as:
var lat = Model.latitude.ToString("0.#####", CultureInfo.CreateSpecificCulture("en-GB"));
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.
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>