im trying to display google maps using html5 geolocation, the code is working fine is jsfiddle but in my mvc application, the map is not being displayed..posting the code below..
this is the link
http://jsfiddle.net/PhzsR/62/
#{
ViewBag.Title = "Home Page";
}
<h2>#ViewBag.Message</h2>
<div id="results"></div>
<div id="map"></div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var $message_area = jQuery('#results');
jQuery(document).ready(function () {
$message_area.html('<i>Locating you...</i> ');
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function foundLocation(position) {
$message_area.children().remove();
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var accuracy = position.coords.accuracy;
var map;
var centerPosition = new google.maps.LatLng(latitude, longitude);
var options = {
zoom: 12,
center: centerPosition,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($('#map')[0], options);
var marker = new google.maps.Marker({
position: centerPosition,
map: map,
icon: 'http://google-maps-icons.googlecode.com/files/sailboat-tourism.png'
});
var circle = new google.maps.Circle({
center: centerPosition,
radius: accuracy,
map: map,
fillColor: '#0000FF',
fillOpacity: 0.5,
strokeColor: '#0000FF',
strokeOpacity: 1.0
});
map.fitBounds(circle.getBounds());
$message_area.append('Your latitude: ' + latitude + ' and longitude: ' + longitude + ' and accuracy: ' + accuracy + ':')
}, function (error) {
switch (error.code) {
case error.TIMEOUT:
$message_area.append('Timeout error while finding your location');
break;
case error.POSITION_UNAVAILABLE:
$message_area.append('Position unavailable error while finding your location');
break;
case error.PERMISSION_DENIED:
$message_area.append('Permission denied error while finding your location');
break;
case error.UNKNOWN_ERROR:
$message_area.append('Unknown error while finding your location');
break;
}
});
}
});
</script>
do i need to add any reference for displaying google maps?
If you look at the 'manage resources' tab on your fiddle, you've got a reference to Google Maps API which isn't in your code above, make sure you add
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
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 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'm trying to upgrade an app into Rails 3. The app requires a map that can be edited and it has been using google maps and mapstraction. When I upgraded to rails 3 the map stopped showing up and I figured that's because it needed to be updated from google maps api v2 to v3.
I've been trying to use this tutorial to upgrade it but because the app is using mapstraction I've been having difficulty getting it to work.
Initially, this was in the html:
<script src="http://maps.google.com/maps?file=api&v=2&key=<%= GOOGLE_MAPS_KEY %>" type="text/javascript"></script>
<script src="/javascripts/mapstraction/mxn.js" type="text/javascript"></script>
<script src="/javascripts/mapstraction/mxn.core.js" type="text/javascript"></script>
<script src="/javascripts/mapstraction/mxn.google.core.js" type="text/javascript"></script>
And the maps.js was as follows:
var Map = function() {
this.init()
}
$.extend(Map.prototype, {
m : false,
init: function() {
this.m = new mxn.Mapstraction('mapdiv', 'googlev3')
this.m.addControls({pan: true, zoom: 'large', map_type: false})
// this.m.enableScrollWheelZoom()
this.m.setMapType(3)
return this.m
},
addPoint: function(lat, lng, html) {
var myPoint = new mxn.LatLonPoint(lat, lng);
var marker = new mxn.Marker(myPoint);
marker.setInfoBubble(html);
this.m.addMarker(marker);
},
setCenterAndZoom: function(center, zoom) {
this.m.setCenterAndZoom(center, zoom)
},
boundingBox: function(lat1, lon1, lat2, lon2) {
var zoom = this.m.getZoomLevelForBoundingBox(new mxn.BoundingBox(lat1, lon1, lat2, lon2))
var centerlng = (lon1 + lon2) / 2
var centerlat = (lat1 + lat2) / 2
var myPoint = new mxn.LatLonPoint(centerlat, centerlng);
this.m.setCenterAndZoom(myPoint, zoom)
},
addPointToLine: function(lat, lng, line, html, length) {
var point = new mxn.LatLonPoint(lat, lng)
line.points.push(point);
var i = line.points.length
var num = 100
if (i == 1) {
m.addPoint(lat, lng, html)
}
},
addUser: function(lat, lng, avatar, html) {
var marker = new mxn.Marker(new mxn.LatLonPoint(lat, lng));
marker.setInfoBubble(html);
marker.setIcon(avatar);
marker.setIconSize([30,30])
m.m.addMarker(marker);
}
});
I tried changing the html to this (based on the upgrade tutorial and the tutorial from mapstraction):
<script src="//maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script src="http://mapstraction.com/mxn/build/latest/mxn.js?(googlev3)" type="text/javascript"></script>
But when that didn't make a difference I tried to remove mapstraction and change the maps.js to the following:
var Map = function() {
this.init()
}
$.extend(Map.prototype, {
m : false,
init: function() {
this.m = new google.maps.Map(document.getElementById('mapdiv'), {zoom: 13, mapTypeId: google.maps.MapTypeId.HYBRID});
// this.m.addControls({pan: true, zoom: 'large', map_type: false})
// this.m.enableScrollWheelZoom()
// this.m.setMapType(3)
return this.m
},
addPoint: function(lat, lng, html) {
var myPoint = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker(myPoint);
marker.setInfoBubble(html);
this.m.addMarker(marker);
},
setCenterAndZoom: function(center, zoom) {
this.m.setCenterAndZoom(center, zoom)
},
boundingBox: function(lat1, lon1, lat2, lon2) {
var zoom = this.m.getZoomLevelForBoundingBox(new google.maps.LatLonAltBox(lat1, lon1, lat2, lon2))
var centerlng = (lon1 + lon2) / 2
var centerlat = (lat1 + lat2) / 2
var myPoint = new google.maps.LatLng(centerlat, centerlng);
this.m.setCenterAndZoom(myPoint, zoom)
},
addPointToLine: function(lat, lng, line, html, length) {
var point = new google.maps.LatLng(lat, lng)
line.points.push(point);
var i = line.points.length
var num = 100
if (i == 1) {
m.addPoint(lat, lng, html)
}
},
addUser: function(lat, lng, avatar, html) {
var marker = new google.maps.Marker(new google.maps.LatLng(lat, lng));
marker.setInfoBubble(html);
marker.setIcon(avatar);
marker.setIconSize([30,30])
m.m.addMarker(marker);
}
});
But still nothing...does anyone have any idea how I can get the map to display?
Thanks
as it seems your code uses jQuery($.extend), did you include jQuery?
all the method you've defined are methods of Map but you try to call these methods for Map.m(which is a google.map.Map-instance and doesn't have such methods)
I don't see where you create the Map-instance(I mean your "class", not the google.maps.Map) at all
a google.maps.Map requires a center-property which is not present(at least not when you create the google.maps.Map-instance in Map.init())
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 want to display several placemarkers on the map with the help of lat's and long's that I have in my controller. There are no build errors and I am also able to see the map with the various placemarker but only the last info window is responding to the click event.
#section Script {
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
}
<div id="map_canvas" style="width: 875px; height: 600px">
</div> `
<script type="text/javascript">
//display the map
var stockholm = new google.maps.LatLng(59.32522, 18.07002);
var myOptions = {
zoom: 4,
center: stockholm,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//display markers
#foreach (var item in Model)
{
<text>
var latLng = new google.maps.LatLng('#(item.Latitude)', '#(item.Longitude)');
var title = '#(item.Title)';
var contentString = '<h3>' + title + '</h3>'
var marker = new google.maps.Marker({
position: latLng,
map: map
});
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(contentString);
infoWindow.open(map, marker);
});
</text>
}
</script>
For each item in the model you are creating a marker. However the code to add the event listener to the marker (for the click ) is outside of the loop.
The event listener is only being added to the last marker, not every marker.