I'm trying to direct to a page on my project from the Index (project homepage).
It worked only once.
This code is from the parkingLotscontroller
public ActionResult TotalPs()
{
ViewBag.Message = "TotalPs";
var totalQuery =
(from lot in db.parkingLots
orderby lot.PricePerHour
select new
{
ID = lot.parkingLotID,
address = lot.addressParkingLot,
latitude = lot.latitudeParkingLot,
longtitude = lot.longtitudeParkingLot,
Status = lot.statusParkingLot,
PricePerHour = lot.PricePerHour
})
.Union(from pub in db.publicParkings
orderby pub.PricePerHourpublicParking
select new
{
ID = pub.publicParkingID,
address = pub.addressPublicParking,
latitude = pub.latitude,
longtitude = pub.longtitude,
Status = pub.statusParking,
PricePerHour = pub.PricePerHourpublicParking
});
var data2 = totalQuery.ToList();
var jsonString2 = JsonConvert.SerializeObject(data2);
if (jsonString2 != null)
{
if (!Directory.Exists(Server.MapPath("~/Content/")))
{
Directory.CreateDirectory(Server.MapPath("~/Content/"));
}
}
System.IO.File.WriteAllText(Server.MapPath("~/Content/TotalJson.json"), jsonString2);
db.SaveChanges();
return View();
}
This code is from the view
#{
ViewBag.Title = "TotalPs";
}
<h2>TotalPs</h2>
<head>
<style>
#map {
height: 700px;
width: 1000px;
border: 1px solid black;
margin: 0 auto;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyApsEFrg9i2dlhq493ME30ETlDGDNbQvWI" type="text/javascript"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<br />
<br />
<div class="topnavI" align="center">
<p style="font-size:16px;"> Enter the address to search for available parking spaces</p>
<input type="text" placeholder="Search for address" size="40">
</div>
<br />
<br />
<div id="map"></div>
<script>
var map;
function initialize() {
var mapProp = {
center: new google.maps.LatLng(32.04772750000001, 34.7609645),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), mapProp);
};
$(document).ready(function () {
var url = "../../Content/TotalJson.json";
initialize();
$.getJSON(url, function (data) {
$.each(data, function (i, field) {
$('#list').append("<li>" + data[i].latitude + " & " + data[i].longtitude + "</li>");
createMarker(data);
function createMarker(data) {
var marker = new google.maps.Marker({
icon: 'https://maps.google.com/mapfiles/kml/shapes/parking_lot_maps.png',
position: new google.maps.LatLng(data[i].latitude, data[i].longtitude),
map: map,
title: field.crossroad
});
};
});
});
});
</script>
<body>
</body>
And the Index page
#Html.ActionLink("INBAL", "TotalPs", "parkingLots")
So on server side it works perfectly and the view immediatly comes up,
but on cliet side it takes a while to load and then
throws an error.
What is the problem and how do I fix it?
Thanks!
Just make a controller action that returns the JSON and call it from the client instead of writing to a file. If multiple users hit your application, multiple processes are going to attempt to write to the same file and error out.
public ActionResult TotalPs()
{
ViewBag.Message = "TotalPs";
return View();
}
public JsonResult TotalPData()
{
var totalQuery =
(from lot in db.parkingLots
orderby lot.PricePerHour
select new
{
ID = lot.parkingLotID,
address = lot.addressParkingLot,
latitude = lot.latitudeParkingLot,
longtitude = lot.longtitudeParkingLot,
Status = lot.statusParkingLot,
PricePerHour = lot.PricePerHour
})
.Union(from pub in db.publicParkings
orderby pub.PricePerHourpublicParking
select new
{
ID = pub.publicParkingID,
address = pub.addressPublicParking,
latitude = pub.latitude,
longtitude = pub.longtitude,
Status = pub.statusParking,
PricePerHour = pub.PricePerHourpublicParking
});
return Json(totalQuery);
}
and then
$(document).ready(function () {
var url = "#Url.Action("TotalPData", "ParkingLots")";
I have no idea why you are calling db.SaveChanges() since you are only reading data and not updating anything.
Related
This question already has answers here:
Google Maps API v3: How to remove all markers?
(32 answers)
Closed 4 years ago.
Could someone be kind enough to share how I can clear the markers in google map before refreshing it with a new set of markers?
In my map, I'm adding markers from an array that contains name, lat and long. The name can be picked from a drop down menu, and then all the markers for that name are added to the page.
Prtoject : Asp.Net Mvc
Link image: https://i.hizliresim.com/V927Py.jpg
When the user adds markers, the previous set of markers remain. I'd like to remove any existing markers before adding the new set.
After reading the documentation, I tried this:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#model List<Project_Map.Models.KONUM>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Complex Marker Icons</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<style>
#map_wrapper {
height: 700px;
}
#map_canvas {
width: 100%;
height: 100%;
}
</style>
<div id="map_wrapper">
<div class="mapping" id="map_canvas">
</div>
</div>
<div id="map"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
jQuery(function ($) {
var script = document.createElement('script');
script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyBT56XlfxnK2OB4K93vWdrZci_CKjZyQOM&callback=initMap";
document.body.appendChild(script);
});
</script>
<!-- Google Maps Kodu -->
<script type="text/javascript">
var contentString = '<div id="content">' +
'<div id="siteNotice">' +
'<img src="#IMG_SRC#" />' +
'</div>' +
//'<h2 id="firstHeading" class="firstHeading">#PERSONEL#</h2>' +
'<div id="bodyContent">' +
'<b>Mesafe: </b>#MESAFE# Km<br />' +
'<b>Tarih: </b> #TARIH#' +
'</p>' +
'</div>' +
'</div>';
$(document).ready(function () {
initMap();
});
function initMap() {
var mapCenter = { lat: 39.684536, lng: 35.337094 };
var map = new google.maps.Map(document.getElementById('map_wrapper'), {
zoom: 6,// haritanın yakınlık derecesi
center: mapCenter, // haritanın merkezi
mapTypeId: google.maps.MapTypeId.HYBRID
});
var infoWindow = new google.maps.InfoWindow();
setInterval(function () {
$.ajax({
url: '#Url.Action("GetMapLocations", "Konum")',
type: "POST",
success: function (data) {
var json = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
var position = {
lat: parseFloat(json[i].lat.replace(',', '.')),
lng: parseFloat(json[i].lng.replace(',', '.'))
};
var marker = new google.maps.Marker({
position: position,
animation: google.maps.Animation.BOUNCE,
map: map,
});
// infoWindow içeriğini replace et
var cs = contentString;
cs = cs.replace("#PERSONEL#", json[i].name);
cs = cs.replace("#MESAFE#", json[i].mesafe);
cs = cs.replace("#TARIH#", json[i].tarih);
cs = cs.replace("#IMG_SRC#", json[i].img);
google.maps.event.addListener(marker, 'click', (function (marker, cs, infoWindow) {
return function () {
infoWindow.setContent(cs);
infoWindow.open(map, this);
passive: true;
};
})(marker, cs, infoWindow));
};
},
error: function (data) { alert("Malesef Sunucunuza Ulaşamıyoruz. Lütfen Tekrar Deneyiniz..."); },
});
}, 5000);
};
</script>
</body>
</html>
You have to set up an array, where you can store the added marker
var gmarkers = [];
If you add a marker you have to store the marker object in the array.
gmarkers.push(marker);
If you want to remove these markers you can use something like:
function removeMarker() {
if (gmarkers.length > 0) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i] != null) {
gmarkers[i].setMap(null);
}
}
}
gmarkers = [];
}
I'm using Google Maps on a ruby on rails site. Code is below:
<div id="map" style='width: 1170px; height: 500px;'></div>
<script>
var map;
function initialize() {
map = new google.maps.Map(document.getElementById('map'));
var json = <%=raw #places.to_json %>;
var data;
var service = new google.maps.places.PlacesService(map);
var bounds = new google.maps.LatLngBounds();
if (json.length == 0) {
map.setCenter({lat: 40.736, lng: -73.991});
map.setZoom(11);
}
else {
for (var i = 0, length = json.length; i < length; i++) {
data = json[i].google_key;
if(data != null) {
service.getDetails({placeId: data},function(results, status){
if (status == google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
place: {
placeId: results.place_id,
location: results.geometry.location
},
});
bounds.extend(results.geometry.location);
map.fitBounds(bounds);
}
});
}
}
}
googleAutocomplete();
}
function googleAutocomplete() {
var input = document.getElementById('place_name');
var autoComplete = new google.maps.places.Autocomplete(input);
autoComplete.addListener('place_changed', function() {
var place = autoComplete.getPlace();
document.getElementById('place_name').value = place.name;
document.getElementById('place_google_key').value = place.place_id;
});
}
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA68X13MKpg02y8ZdpKtOUociJqhAg8QyY&libraries=places&callback=initialize" async defer></script>
I get the following error:
You have included the Google Maps API multiple times on this page. This may cause unexpected errors.
I would appreciate any help.
I think your issue is related to turbo-links. Try adding this line to your script tag and see if the error goes away.
data-turbolinks-eval="false"
So your new script tag should look like this:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA68X13MKpg02y8ZdpKtOUociJqhAg8QyY&libraries=places&callback=initialize" data-turbolinks-eval="false" async defer></script>
Let me know if that helps.
I have a google maps piece of code that gets my current location to a fixed destination but the width and height of the view wont stay the same after i click on the button to get the directions and it looks very unprofessional
The width and height changes once i click on the button. I want the size of the maps to stay the same as before i click the button and once i click the button the size of the maps should remain the same as before and not change
This is the code i have:
<!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>
<h2>Our Location</h2>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC6v5-2uaq_wusHDktM9ILcqIrlPtnZgEk&sensor=false">
</script>
<script type="text/javascript">
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
alert("There is Some Problem on your current browser to get Geo Location!");
}
function success(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var city = position.coords.locality;
var LatLng = new google.maps.LatLng(lat, long);
var mapOptions = {
center: LatLng,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("MyMapLOC"), mapOptions);
var marker = new google.maps.Marker({
position: LatLng,
title: "<div style = 'height:60px;width:200px'><b>You Are Here:</b><br />Latitude: "
+ lat + +"<br />Longitude: " + long
});
marker.setMap(map);
var getInfoWindow = new google.maps.InfoWindow({ content: "<b>Your Current Location</b><br/> Latitude:" +
lat + "<br /> Longitude:" + long + ""
});
getInfoWindow.open(map, marker);
}
</script>
<script type="text/javascript">
function SearchRoute() {
document.getElementById("MyMapLOC").style.display = 'none';
var markers = new Array();
var myLatLng;
//Find the current location of the user.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p) {
var myLatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
var m = {};
m.title = "Your Current Location";
m.lat = p.coords.latitude;
m.lng = p.coords.longitude;
markers.push(m);
//Find Destination address location.
var address = document.getElementById("txtDestination").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
m = {};
m.title = address;
m.lat = results[0].geometry.location.lat();
m.lng = results[0].geometry.location.lng();
markers.push(m);
var mapOptions = {
center: myLatLng,
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("MapRoute"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var data = markers[i];
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
});
latlngbounds.extend(marker.position);
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.title);
infoWindow.open(map, marker);
});
})(marker, data);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
//***********ROUTING****************//
//Initialize the Path Array.
var path = new google.maps.MVCArray();
//Getting the Direction Service.
var service = new google.maps.DirectionsService();
//Set the Path Stroke Color.
var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' });
//Loop and Draw Path Route between the Points on MAP.
for (var i = 0; i < lat_lng.length; i++) {
if ((i + 1) < lat_lng.length) {
var src = lat_lng[i];
var des = lat_lng[i + 1];
path.push(src);
poly.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
} else {
alert("Invalid location.");
window.location.href = window.location.href;
}
});
}
}
} else {
alert("Request failed.")
}
});
});
}
else {
alert('Some Problem in getting Geo Location.');
return;
}
}
</script>
</head>
<body>
<form id="SetDirections">
<p>Directions To Elena's Delicacies</p>
<p>
<b>Elena's Delicacies Address:</b>
<input type="text" id="txtDestination" value="499 Paradise Valey Pinetown" style="width: 300px"disabled readonly />
<input type="button" value="Directions" onclick="SearchRoute()" />
</p>
<div id="MyMapLOC" style="width: 100%; height: 600px">
</div>
<div id="MapRoute" style="width: 500px; height: 500px">
</div>
</form>
</body>
</html>
I am displaying a list of locations (that i get through ViewBag for now) on a map and ask the user to choose one of them.
I have populated my infowindows with HTML code by looping through the list of locations.
now when the user clicks on one of the buttons in the infowindow ("Choose this one"), I want to update the view model (Venue) to include Venue.Id = the choosen location and submit back to the controller so update the database. how can I do such a thing ?
thanks a lot for your help.
here is my script code:
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<section class="scripts">
<script type="text/javascript">
$(document).ready(function () {
Initialize();
});
function Initialize() {
google.maps.visualRefresh = true;
var rabat = new google.maps.LatLng(34.019657, -6.831833);
var mapOptions = {
zoom: 11,
center: rabat,
mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var list =
#Html.Raw(Json.Encode(((IEnumerable<KayenChiMVC.Models.Venue>)ViewBag.TheVenue).Select(v => new
{
venueId = v.VenueID,
venueName = v.Name,
venueDistrict = v.District,
venueType = v.SurfaceType,
venueLat = v.Latitude,
venueLon = v.Longitude
})
));
var infowindow = new google.maps.InfoWindow();
for(var i=0; i<list.length;i++){
var pos = new google.maps.LatLng(list[i].venueLat, list[i].venueLon);
var html = "<table>" +
"<tr><td>Nom:</td>" + "<td> " + list[i].venueName +" </td> </tr>" +
"<tr><td>Quartier:</td>" + "<td> " + list[i].venueDistrict +" </td> </tr>" +
"<tr><td>Type de surface:</td>" + "<td> " + list[i].venueType +" </td> </tr>" +
"<tr><td></td><td><input type='button' value='Choisir ce terrain' onclick=''/></td></tr>";
createMarker(pos, list[i].venueName, html);
function createMarker(pos,title, html){
var marker = new google.maps.Marker({
'position': pos,
'map': map,
'title': list[i].venueName
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/red-dot.png');
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(html);
infowindow.open(map, marker);
});
}
}
}
</script>
</section>
Add a data-id attribute to your input to hold the venue id.
<input id="myButton" type="button" data-id="123" value="Choose this one" />
and get the data-id attribute in javascript
document.getElementById('myButton').onclick = function() {
console.log(this.getAttribute('data-id')); // will log '123'
};
I've been working on this for a couple so getting to this point should make me very happy. However, I cannot figure out my infowindow output is adding "\n" to every new line. No idea how it's getting there. The geolocation is also being appended to the search result infowindow. I'd like to remove that as well.
Here is a link to the map: http://58design.com/gmaps/
Here is my 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>Sheriff | Zone Leader Look Up</title>
<meta name="author" content="Santa Clarita Valley Sheriff" />
<meta name="copyright" content="Copyright 2013 SCV Sheriff" />
<meta name="keywords" content="Santa Clarita Valley Sheriff, SCV Sheriff, Canyon Country, Valencia, Saugus, Newhall, Castaic, Gorman, Stevenson Ranch, " />
<meta name="description" content="Santa Clarita Valley Sheriff Zone Leader Contact Inforamtion Look Up." />
<meta name="robots" content="index,follow" />
<meta name="Googlebot" content="follow" />
<meta name="googlebot" content="archive" />
<meta name="distribution" content="global" />
<!--Load the AJAX API-->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
google.load('visualization', '1', {'packages':['corechart', 'table', 'geomap']});
//var FusionTableID = 1931355;
var FusionTableID = '1uSGM1yPMJBlu74Znm4fPqdCsJjteB_kQ_nGz3tk';
var map = null;
var geocoder = null;
var infowindow = null;
var marker = null;
function initialize() {
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow({size: new google.maps.Size(150,50) });
// create the map
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(34.452789398370045, -118.51948001245114),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
//layer = new google.maps.FusionTablesLayer(FusionTableID,{suppressInfoWindows:true});
layer = new google.maps.FusionTablesLayer({
map: map,
suppressInfoWindows: true,
heatmap: { enabled: false },
query: {
select: "col2",
from: "1uSGM1yPMJBlu74Znm4fPqdCsJjteB_kQ_nGz3tk",
where: "",
},
options: {
styleId: 2,
templateId: 2
}
});
layer.setMap(map);
google.maps.event.addListener(layer, "click", function(e) {
var content = e.row['description'].value+"<br><br>";
infowindow.setContent(content);
infowindow.setPosition(e.latLng);
infowindow.open(map);
});
}
function showAddress(address) {
var contentString = address+"<br>Outside Area";
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var point = results[0].geometry.location;
contentString += "<br>"+point;
map.setCenter(point);
if (marker && marker.setMap) marker.setMap(null);
marker = new google.maps.Marker({
map: map,
position: point
});
// query FT for data
var queryText ="SELECT 'description', 'Zone Area' FROM "+FusionTableID+" WHERE ST_INTERSECTS(\'Zone Area\', CIRCLE(LATLNG(" + point.toUrlValue(6) + "),0.5));";
// document.getElementById('FTQuery').innerHTML = queryText;
queryText = encodeURIComponent(queryText);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(openInfoWindowOnMarker);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function openInfoWindowOnMarker(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
FTresponse = response;
//for more information on the response object, see the documentation
//http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
var content = "<b>Outside area</b><br><br>";
var unionBounds = null;
// alert(numRows);
for (var i=0; i < numRows; i++) {
var name = FTresponse.getDataTable().getValue(i,0);
var kml = FTresponse.getDataTable().getValue(i,1);
content = response.getDataTable().getValue(i,0)+"<br><br>";
}
infowindow.setContent(content+marker.getPosition().toUrlValue(6));
// zoom to the bounds
// map.fitBounds(unionBounds);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
google.maps.event.trigger(marker, 'click');
}
</script>
</head>
<body onload="initialize()">
<div id="content">
<h1>SCV Sheriff Reporting Zones</h1>
<p>Use the map below to determine your area's Zone Leader. Enter your street address, city and zip code in the search field below to view the Zone Leader's contact info.</p>
<form action="#" onsubmit="showAddress(this.address.value); return false" style="padding:10px 0px 30px 0px; background:none;">
<label>Address Search</label>
<input type="text" size="60" name="address" value="23920 Valencia Blvd. Santa Clarita, CA 91355" class="address" />
<input type="submit" value="Search" />
</p>
<div id="map_canvas" style="width: 516px; height: 387px; margin-bottom:30px; border:1px solid #999;"></div>
</form>
</div>
<div id="sidebar">
</div>
<div class="clear"><!--clear--></div>
</div>
</body>
</html>
The problem is in the data in your FusionTable (the line feeds are getting translated into "\n"). I fixed the entry for "Gorman" in my example (by removing the extraneous line feeds).
This line of my code is appending the geolocation to the search result infowindow:
infowindow.setContent(content+marker.getPosition().toUrlValue(6));