I'm trying to get checkboxes to set polygons to visible/non visible on a map. As per the code below it does not work. I presume because the variable type I am passing is incorrect/needs to be cast. But I'm not sure...
How can I write this code so that the area/polygon associated with the checkbox (of the same name) has its visibility toggled?
To be honest I'm new to Javascript and I'm sure I've missing something easy but any help would be appreciated!
<script>
var cheyChumneahCoords = [
new google.maps.LatLng(11.567148,104.931901),
new google.maps.LatLng(11.564994,104.925757),
new google.maps.LatLng(11.559585,104.927309),
new google.maps.LatLng(11.562065,104.933274),
new google.maps.LatLng(11.562276,104.935892),
new google.maps.LatLng(11.562234,104.935935),
new google.maps.LatLng(11.562108,104.935977)
];
// Chey Chumneah area
var cheyChumneahArea=new google.maps.Polygon({
path:cheyChumneahCoords,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:0,
fillColor:"#0000FF",
fillOpacity:0.4
});
function areaChange(areaName, checked)
{
alert("Area " + areaName + " changed and is checked: " + checked); //Debug
cheyChumneahArea.setVisible(checked); //Works
areaName.setVisible(checked); //Does not work
}
function initialize()
{
var mapProp = {
center:new google.maps.LatLng(11.562276,104.919434),
zoom:14,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap")
,mapProp);
cheyChumneahArea.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap"></div>
<div id="areaSelection">
<input type="checkbox" name="areas" value=cheyChumneahArea onchange="areaChange(this.value, this.checked)">Chey Chumneah<br>
<input type="checkbox" name="areas" value="BKK1Area" onchange="areaChange(this.value, this.checked)">BKK1
</div>
</body>
</html>
areaName is a string, not an object.
Use the subscript-notation:
window[areaName].setVisible(checked);
Related
I am trying to make a single page webapp for displaying markers on a list of places and their corresponding info Windows using knockoutjs. Following is the code.
<head>
<title>Google maps</title>
<link rel=stylesheet type=text/css href='css/style.css'>
</head>
<body>
<div class="container">
<div class="options-box">
<h1>Liverpool Pubs and Bars - Anfield</h1>
<hr>
<div>
<input id="filter-area" type="text" placeholder="Enter your favorite Pub">
<input id="filter-button" type='button' value="Filter">
</div>
<hr>
<div>
<ul data-bind='foreach: allPlaces'>
<li data-bind='text: name'></li>
</ul>
</div>
</div>
<div id='map'></div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places,geometry,drawing&key=MYAPIKEY&callback=initMap"
async defer></script>
<script type="text/javascript" src="js/knockout-3.2.0.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
JS code.
var ViewModel = function (googleMap, myPlaces, infoWindow) {
var self = this;
self.map = googleMap;
self.allPlaces = [];
self.markers = [];
myPlaces.forEach(function(place) {
newObj = new Place(place);
title = newObj.name;
console.log(title);
// Getting the geocode for the place.
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': place.address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
marker = new google.maps.Marker({
map: self.map,
position: results[0].geometry.location,
animation: google.maps.Animation.DROP,
title: title
});
self.markers.push(marker);
(function (marker, title) {
google.maps.event.addListener(marker, 'click', function (e) {
infoWindow.setContent(title);
infoWindow.open(self.map, marker);
});
})(marker, title);
}
});
self.allPlaces.push(newObj);
});
}
var Place = function(data) {
this.name = data.name;
this.address = data.address;
}
var createMap = function () {
var map;
// Constructor creates a new map - only center and zoom are required.
// Centering map at Anfield.
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 53.4308294, lng: -2.96083},
mapTypeControl: false,
zoom: 13
});
return map;
}
function initMap() {
google.maps.event.addDomListener(window, 'load', function(){
// list of my places.
var myPlaces = [
{
name: 'The Albert',
address: '185 Walton Breck Rd, Liverpool L4 0RE, UK'
},
{
name: 'Arkles',
address: '77 Anfield Rd, Liverpool L4 0TJ, UK'
},
{
name: 'The Sandon',
address: '178-182 Oakfield Rd, Liverpool L4 0UH, UK'
},
{
name: 'The Park Pub',
address: '216-218 Walton Breck Rd, Liverpool L4 0RQ, UK'
},
{
name: 'The Twelfth Man',
address: '121 Walton Breck Rd, Liverpool L4 0RD, UK'
}
];
var googleMap = createMap();
var infoWindow = new google.maps.InfoWindow();
ko.applyBindings(new ViewModel(googleMap, myPlaces, infoWindow))
});
}
function populateInfoWindow(marker, infowindow) {
// Check to make sure the infowindow is not already opened on this marker.
if (infowindow.marker != marker) {
infowindow.marker = marker;
infowindow.setContent('<div>' + marker.title + '</div>');
infowindow.open(map, marker);
// Make sure the marker property is cleared if the infowindow is closed.
infowindow.addListener('closeclick',function(){
infowindow.setMarker = null;
});
}
}
The rest of the map driven code is regular initMap function. The initMap function creates a infowindow, initializes a list of places with name and address attributes. And the google is initialized.
The markers are appearing correctly, though clicking on them opens the info window with only the name of last element. Is it something related to JS closures? How can I implement an IFFE here. Would it solve the issue.
Never mind, added var to the statements newObj and title and the problem was fixed.!!
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 trying to load a couple of LatLongs from an SQL DB into a Google Maps API on a webpage. I've been following this tutorial, even to the point of copying code straight from it since I'm such a Javascript noob.
What I have so far is:
-Coordinates can be added from the form on the right side of the page (they show up in phpMyAdmin)
-The php script to make an xml of the LatLongs works flawlessly (what do you mean I only get 2 links?)
The problem USED TO BE that the markers wouldn't show up on the map, but the map still loaded. After I tried rewriting the page to better match the code in the tutorial, the map itself won't load. I've read through some other threads on SE related to problems with this tutorial, but nothing in those seems to work...
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBvwCMuLz31gLXoawbDBntieQjGPMrf5vA" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
well: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(55.000, -115.000),
zoom: 6
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("create_xml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
</head>
<body onload="load()">
<div id="map" style="float:left; width:50%;"></div>
Thanks in advance!
Your current problem is your map doesn't have a size. You changed this:
<div id="map" style="width: 500px; height: 300px"></div>
to:
<div id="map" style="float:left; width:50%; height:100%"></div>
For that to work you also need to add additional css:
html, body {
height: 100%;
width: 100%;
}
Proof of concept snippet:
var customIcons = {
well: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(55.000, -115.000),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infoWindow = new google.maps.InfoWindow();
}
load();
html,
body {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3" type="text/javascript"></script>
<div id="map" style="float:left; width:50%; height:100%;"></div>
<div style="float:right; width:50%;">
<h1>WellMap</h1>
<br>
<!-- <img src="well_icon.png"> -->
<br>
<form name="new_well" method="" action="">
Well Name:
<input type="text" name="wellName" id="wellName"/>
<br/>Well Latitude:
<input type="text" name="wellLat" id="wellLat" />
<br/>Well Longitude:
<input type="text" name="wellLong" id="wellLong" />
<br/>
<input type="submit" name="submit" value="Add Well" />
</form>
</div>
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 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>