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"));
Related
I am trying to use Google Gecoding API so that I can get the coordinates from a street address and use it with Google Maps. When I was just using the Google map I had no problems getting it to work. I have been following a guide since I don't really understand JavaScript. I get the error
ReferenceError: google is not defined
when I open the inspect element console.
I have been googling and I think the problem is that the map is not initialized when I run the first part of my JavaScript, since I only get the error on the Geocoding part. But I don't know what to do or how to fix it. Would appreciate some help.
Here is my view:
<div class="full">
<div class="saloon-main col-md-8">
<h1 class="display-2">#Model.SaloonName</h1>
<p class="saloon-adress">Andress 99 PostNr, Stad / TelNr: +46 21-123 45</p>
<button type="button" class="btn-primary">Boka tid</button>
</div>
<div class="company-right-nav col-md-4">
<div class="col-sm-12 saloon-info">
<ul class="list-unstyled">
<li>#Model.SaloonName</li>
<li>Email: #Model.Email</li>
<li>Telefon</li>
<li>Adress</li>
</ul>
<ul>
<li>ÖPPETTIDER</li>
<li>MÃ¥ndag:</li>
</ul>
</div>
<div id="map">
<p>map</p>
</div>
</div>
<div class="clear"></div>
</div>
<script>
geocoder = new google.maps.Geocoder();
function getCoordinates (adress, callback) {
var coordinates;
geocoder.geocode({ adress: adress }, function (results, status) {
coords_obj = results[0].geometry.location;
coordinates = [coords_obj.nb,coords_obj.ob];
callback(coordinates);
})
}
var map;
function initMap() {
getCoordinates('4203 las palmas austin texas', function(coords) {
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(coords[0], coords[1]),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'),
mapOptions);
})
}
google.maps.event.AddDomListener(window, 'load', initMap);
</script>
<script async defer src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDfKu9XJ0jr19cj46HYSqQrNDU-oX0LKmY&callback=initMap"
type="text/javascript"></script>
Try below code
No need to trigger event. initMap will automatically call when the library finish loading.
var map;
function initMap() {
geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': '4203 las palmas austin texas' }, function (results, status) {
if (status == 'OK') {
coords_obj = results[0].geometry.location;
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(coords_obj.lat(), coords_obj.lng()),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
<style>
#map {
position: unset !important;
}
</style>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDfKu9XJ0jr19cj46HYSqQrNDU-oX0LKmY&callback=initMap"></script>
<div id="map"></div>
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
How to create a polygon dynamically on google map using jsf with derby database?This code worked for static points but i have dynamic data in points entity. How to get those points and display in google map?
<html>
<head>
<style>
#map {
width: 1200px;
height: 1000px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {lat: 17.68, lng: 83.21},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
// Define the LatLng coordinates for the polygon's path.
var triangleCoords = [
{lat: 18.3000, lng: 83.900},
{lat: 18.1713, lng: 82.1278},
{lat: 17.370, lng: 78.480},
{lat: 17.68, lng: 83.21},
];
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>
you should download gmaps4jsf jar file and use it. GMaps4JSF integrating Google maps with JSF. you can create java beans class and call the value dynamically through JSF. You can refer this http://www.mashups4jsf.com/gmaps4jsf-examples2-3.0.0/pages/welcome.xhtml it will help you.
or Here I am giving one example.
JSF code:
<m:map id="map" width="1080px" height="350px" partiallyTriggered="true" latitude="#{pointBean.mapLatitude}" longitude="#{pointBean.mapLongitude}" enableScrollWheelZoom="true">
<m:polygon id="polygon" lineWidth="2" hexStrokeColor="red" hexFillColor="lightpink">
<ui:repeat var="point" value="#{pointBean.points}" varStatus="status" offset="0" step="1" size="#{pointBean.points.size()}">
<m:point latitude="#{point.latitude.toString()}" longitude="#{point.longitude.toString()}">
</m:point>
</ui:repeat>
</m:polygon>
</m:map>
pointBean class:(java bean class)
private List<Point> points;
private Float mapLatitude;
private Float mapLongitude;//create getter or setter also
public List<Point> getlatlong() {
String query = ".....";//write here your query
points = new ArrayList<Point>();
Point point = null;
ResultSet rs = null;
try {
connection = ConnectionFactory.getConnection();//here is connection for jdbc connectivity
statement = connection.createStatement();
rs = statement.executeQuery(query);
while (rs.next()) {
point = new Point();
point.setLatitude(rs.getFloat("latitude"));
point.setLongitude(rs.getFloat("longitude"));
points.add(point);
}
mapLatitude = points.get(0).getLatitude();
mapLongitude = points.get(0).getLongitude();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
DBUtil.close(rs);
DBUtil.close(statement);
DBUtil.close(connection);
}
return points;
}
public List<Point> getPoints() {
return points;
}
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>
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.