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.
Related
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.
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 have MVC 4 Application and im using google maps to render my locations by retrieving latitude and longitude from the database.(My database is updated automatically by wcf data service through mobile device.)
In MVC Application i want to refresh the google map automatically in timely manner.
Following is my index page(Index.cshtml).
#model IEnumerable<MvcApplication17.Models.Train>
<div id="MapLocators">
#Html.Partial("Map_Locator", Model)
</div>
<script type="text/javascript">
$(function () {
setInterval(function () { $('#MapLocators').load('/Home/GetMap'); }, 3000);
});
</script>
Here is my Partial View under Home(Map_Locator.cshtml),
#model IEnumerable<MvcApplication17.Models.Train>
<div id="content-container">
<div id="map_canvas">
</div>
</div>
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', function(){
var bounds = new google.maps.LatLngBounds();
var mapoptions = { zoom:6}; //map options
var map = new google.maps.Map(document.getElementById('map_canvas'), mapoptions);
map.markers = [];
#foreach(var item in Model)
{
<text>
var poiLatLang = new google.maps.LatLng( #item.Latitude, #item.Longitrude);
var image = 'images/Train station.png';
var marker = new google.maps.Marker({
position: poiLatLang ,
map: map,
icon: image
});
bounds.extend(marker.position);
map.markers.push(marker);
</text>
}
map.fitBounds(bounds);
});
</script>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
Here is my Home Controller,
private TestContext db = new TestContext();
[OutputCache(NoStore = true, Location = OutputCacheLocation.Client, Duration = 3)]
public ActionResult GetMap()
{
return PartialView("Map_Locator",db.Trains.ToList());
}
The problem is index page show the google maps only in first application loading stage and it doesn't refresh automatically.
Thanks
I solved the problem by calling map load function in following way,
<script>
$(function () {
setInterval(function () { $('#MapLocators').load('/Home/GetMap',function{}); }, 20000);
});
</script>
I have a page show_map.html.erb that displays a Google Map (currently working great). I want to add an image instead of the pin marker on the map. I have Googled a lot for this question, and found resources such as this question on StackOverflow. However, my current solution doesn't work.
Do I have to upload an image before using it? Moreover, why can't I use images like public/alert.png OR app/asset/images/alert.png? I referred to the Google Maps API documentation too, but I can't understand the examples.
My controller:
def show_map
#location = Location.find(params[:id])
#address = #location.landmark.gsub(","+")+",+"+#location.place.gsub(","+")+",+"+#location.country
p #address
end
My view:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=<my api key>&sensor=true"> type="text/javascript"></script>
<script type="text/javascript">
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h2 id="firstHeading" class="firstHeading" ><font color="#FF0000"><%=#location.title%></font></h2>'+
'<div id="bodyContent" >'+
'<p><%=#location.description%></p>'+
'<p><a href="http:www.google.com">'+
'more info</a> (created on <%=(#location.created_at).strftime("%A, %d/%m/%Y")%>)</p>'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
//set the image
//var image = '/assets/images/alert.png';
// Enable the visual refresh
google.maps.visualRefresh = true;
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 17,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
//var image = "#{Rails.root}/app/assets/images/alert.png";
//code to search the address
//var address = document.getElementById("address").value;
var address='<%= #address.parameterize %>';
//alert(address);
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(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,
title:"<%=#location.title%>",
animation: google.maps.Animation.DROP,
visible: true,
draggable: true,
icon: image
});
//animation for marker
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.DROP);
}
}
//commented as show the info ON click on the marker
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
//listener for animation
google.maps.event.addListener(marker, 'click', toggleBounce);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
<body onload="initialize()">
<div id="map" align="right" style="min-height: 500px; height: 400px; width: 400px"></div>
</body>
If you're using the gmaps4rails gem and presuming you've added all dependencies and scripts You will will have something very similar to the following in your controller. You would replace "XYZ" and add your own web address.
def index
#XYZs = XYZ.all
#hash = Gmaps4rails.build_markers(#XYZ) do |XYZ, marker|
marker.lat XYZ.latitude
marker.lng XYZ.longitude
marker.infowindow XYZ.artist
marker.picture({
url: "WWW.YourWebAddressHere.com",
width: 32,
height: 32,
})
end
There are live samples and video documentation for the gem that I found quite helpful.
I have implemented the Jquery.mobile.scrollview.js and i am able to scroll the dropdown,But what happens is when i click to scroll the checkboxes inside the dropdown the checkboxes gets invisible and only the text is shown.. IS there is any workaround is there... Please let me know..
IS there any example on this..... I am adding my code below .. and giving data-scroll = 'y' in my div part ...
<!-- Scroll View code -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#evtCatcher
{
}
#evtCatcher .ui-scrollview-view
{
padding: 10px;
}
</style>
<script src="jsScroll/jquery.js" type="text/javascript"></script>
<script src="jsScroll/jsdefault.js" type="text/javascript"></script>
<script src="jsScroll/jquery.easing.1.3.js" type="text/javascript"></script>
<script src="jsScroll/jquery.mobile.scrollview.js" type="text/javascript"></script>
<script src="jsScroll/iscroll.js" type="text/javascript""></script>
<script type="text/javascript">
function fnClick() {
alert('clicked');
}
</script>
<script>
$("[ data-role=page]").live("pageshow", function(event) {
var $page = $(this);
$page.find("[data-scroll]:not(.ui-scrollview-clip)").each(function() {
var $this = $(this);
// XXX: Remove this check for ui-scrolllistview once we've
// integrated list divider support into the main scrollview class.
if ($this.hasClass("ui-scrolllistview"))
$this.scrolllistview();
else {
var st = $this.data("scroll") + "";
var paging = st && st.search(/^[xy]p$/) != -1;
var dir = st && st.search(/^[xy]/) != -1 ? st.charAt(0) : null;
var opts = {};
if (dir)
opts.direction = dir;
if (paging)
opts.pagingEnabled = true;
$this.scrollview(opts);
}
});
changeDelayFormElementClick();
});
function changeScrollMethod() {
var val = $("#s_method").val();
var $sv = $("#evtCatcher").scrollview("scrollTo", 0, 0);
if (val === "scroll") {
$sv.css("overflow", "scroll");
}
else {
$sv.css("overflow", "hidden");
}
$sv.data("scrollview").options.scrollMethod = val;
}
function changeDelayFormElementClick() {
$("#evtCatcher").data("scrollview").options.delayedClickEnabled = ($("#s_delay").val() === "yes");
}
var cb_hd_pd,
cb_hd_sp,
cb_hm_pd,
cb_hm_sp,
cb_hu_pd,
cb_hu_sp;
var hd = $.mobile.scrollview.prototype._handleDragStart;
var hm = $.mobile.scrollview.prototype._handleDragMove;
var hu = $.mobile.scrollview.prototype._handleDragStop;
function getDummyEvent(o) {
return { target: o.target, _pd: false, _sp: false, preventDefault: function() { this._pd = true; }, stopPropagation: function() { this._sp = true; } };
}
function updateEvent(e, cb_pd, cb_sp) {
if (cb_pd.checked)
e.preventDefault();
if (cb_sp.checked)
e.stopPropagation();
}
$.mobile.scrollview.prototype._handleDragStart = function(e, x, y) {
hd.call(this, getDummyEvent(e), x, y);
updateEvent(e, cb_hd_pd, cb_hd_sp);
};
$.mobile.scrollview.prototype._handleDragMove = function(e, x, y) {
hm.call(this, getDummyEvent(e), x, y);
updateEvent(e, cb_hm_pd, cb_hm_sp);
};
$.mobile.scrollview.prototype._handleDragStop = function(e) {
hu.call(this, getDummyEvent(e));
updateEvent(e, cb_hu_pd, cb_hu_sp);
};
$(function() {
cb_hd_pd = $("#cb_hd_pd")[0];
cb_hd_sp = $("#cb_hd_sp")[0];
cb_hm_pd = $("#cb_hm_pd")[0];
cb_hm_sp = $("#cb_hm_sp")[0];
cb_hu_pd = $("#cb_hu_pd")[0];
cb_hu_sp = $("#cb_hu_sp")[0];
});
</script>
Thanks in Advance :)