Why my razor page not show google map? - asp.net-mvc

I'm beginner in asp.net mvc ,i read down tutorial for write simple map web application:
this tutorial
So in my view page write this code:
#section Scripts {
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
}
<h2>Hello, Google Maps</h2>
<div id="map_canvas" style="width:400px; height:300px"></div>
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(40.716948, -74.003563);
var options = { zoom: 14, center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById
("map_canvas"), options);
}
$(function () {
initialize();
});
</script>
but when i run the my project i cant see anything or map,what happen?how can i solve that problem?thanks.
i open firefox browser console and get this message:
The connection to ws://localhost:48472/fbc4eb4ba8f245c08d4b7830ea1bab80/browserLinkSignalR/connect?transport=webSockets&connectionToken=AQAAANCMnd8BFdERjHoAwE%2FCl%2BsBAAAAVMxSNM8YWkSjTNqVKDW%2FRgAAAAACAAAAAAAQZgAAAAEAACAAAABdm%2BiuJnxhF10BzDr1Z%2B7J6KR%2F%2BuJCWYOVuUONt67r8gAAAAAOgAAAAAIAACAAAACcPWAkFxp3Ue2b%2Fu4pg3M7Y3PvHkDLNZfT2ohQfLpWcDAAAAAeHVeKECzTOS87AKunnn2HMxQVjyac86hh6M%2FTjYF4YXxInAmM5wmBizj7UnQW32JAAAAAPgk7BG3rmPAhFQeTmLPjNLjB2Ow%2FbyNdPE5HyR4%2BRmJG3IdLX2om1zux8pxGME9jhfhw3C3AP0e1r5y1JrLtAw%3D%3D&requestUrl=http%3A%2F%2Flocalhost%3A31095%2FGoogleMap%2FGoogleMap&browserName=Firefox&userAgent=Mozilla%2F5.0+(Windows+NT+10.0%3B+WOW64%3B+rv%3A43.0)+Gecko%2F20100101+Firefox%2F43.0&tid=6 was interrupted while the page was loading. browserLink:62:20265
ReferenceError: $ is not defined
GoogleMap:33:5
Use of getPreventDefault() is deprecated. Use defaultPrevented instead.

You don't need jquery for run initialize you simply can add
google.maps.event.addDomListener(window, 'load', initialize);
.
this way
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(40.716948, -74.003563);
var options = { zoom: 14, center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById
("map_canvas"), options);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
try using
#section Scripts {
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?"></script>
}

You need to use either Jquery
or simply call the method at bottom so the whole code should be like
function initialize() {
var latlng = new google.maps.LatLng(40.716948, -74.003563);
var options = { zoom: 14, center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("map_canvas"), options);
}
initialize();
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<h2>Hello</h2>
<div id="map_canvas" style="width:400px; height:300px"></div>
initialize();
and it should work.

Related

How to show google map in MVC?

I want to show Google map on my website and my codes are below but after my page loaded in browser i got this error:
Oops! Something went wrong.
This page didn't load Google Maps correctly. See the JavaScript console for
technical details.
I looked at it in Chrome and found this:
Google Maps API error: MissingKeyMapError
https://developers.google.com/maps/documentation/javascript/error-
messages#missing-key-map-error
what is MissingKeyMap?
my codes:
in header tag:
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
<link href="~/Content/Site.css" rel="stylesheet" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?
sensor=false"></script>
<script type="text/javascript">
function initialize() {
var canvas = $("#map_canvas");
var latitude = 35.78334;
var longitude = 51.42511;
var latlng = new google.maps.LatLng(latitude, longitude);
var options = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(canvas[0], options);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(latitude, longitude),
map: map
});
}
$(function () {
initialize();
});
</script>
On my view :
<div style="width: 100%; height: 100%">
<div id="map_canvas" style="width:100%; height:100%; margin-left: 100px"></div>
</div>
In your js code for google maps, you may find something like this https://maps.googleapis.com/maps/api/js?key=YOURKEYHERE&callback=initMap
Replace YOURKEYHERE with a google API key of your own. Go to this link to get a key of your own and replace it with YOURKEYHERE and it should work fine.
It's all explained here.
https://developers.google.com/maps/documentation/javascript/get-api-key
You need to provide a api-key in the url of your javascript
<script async defer src="https://maps.googleapis.com/maps/api/js? key=YOUR_API_KEY&callback=initMap" type="text/javascript"></script>

how to load Maps after onDeviceReady function in iOS Cordova based app?

I want to Load maps after oDeviceReady function to avoid a Permission alert to access Maps in iOS which shows complete bundle path location as shown below:(iOS Cordova 3.8.0 version)
For this I have used
<link rel="stylesheet" href="css/jquery.mobile-1.4.5.min.css" />
<script src="cordova.js"></script>
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/jquery.mobile-1.4.5.min.js"></script>
<script src="js/hashmap.js"></script>
After head tag:
</head>
<body onload="onBodyLoad();">//Called onload
After this
function onBodyLoad()
{
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady(){
return navigator.geolocation.getCurrentPosition(initialize);
document.addEventListener("backbutton", onBackKeyDown, false);
}
function initialize()
{
geocoder = new google.maps.Geocoder();
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function (p)
{
LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
map = new google.maps.Map(document.getElementById("estimate"), mapOptions);
infowindow = new google.maps.InfoWindow();
marker =new google.maps.Marker({position:LatLng,map:map});
getAddress(p.coords.latitude,p.coords.longitude);
}
}
}
//This line is making to display complete Bundle path loaction
//Where as calling this line to avoid error in onDeviceready, My maps are not loading
// Suggest me where should I call this line of code to avoid this alert
google.maps.event.addDomListener(window, 'load', initialize);
function getAddress(lat, lng)
{
//Code to get address
}
Can anyone suggest me where should I call below line to avoid this type alert;
google.maps.event.addDomListener(window, 'load', initialize);
Other than this alert my code is working fine...
Make sure you installed the geolocation plugin with
cordova plugin add cordova-plugin-geolocation
and change your code to
function onBodyLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady(){
navigator.geolocation.getCurrentPosition(initialize);
document.addEventListener("backbutton", onBackKeyDown, false);
}
function initialize(p) {
geocoder = new google.maps.Geocoder();
LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
map = new google.maps.Map(document.getElementById("estimate"), mapOptions);
infowindow = new google.maps.InfoWindow();
marker =new google.maps.Marker({position:LatLng,map:map});
getAddress(p.coords.latitude,p.coords.longitude);
}
first of all add this plugin using command prompt(cmd)
cordova plugin add org.apache.cordova.geolocation
<div id="map" style="width:100%; height:500px;"></div>
<script>
$(document).ready(function () {
var geocoder;
var map;
function initialize()
{
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: 12
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
codeAddress();
}
google.maps.event.addDomListener(window, 'load', initialize);
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
});
}
});
</script>

MVC 4 PartialView

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>

HTML5 Bing Maps and Geolocation

I'm working on an windows 8 app in html5 and now I'm stuck with the map that is going to find the users location I don't know whats wrong, it says it some error I hope someone can help me because I have more to work on and i have a deadline on this project
map.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>BingMapsJSIntro</title>
<script src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0" type="text/javascript"></script>
<!-- WinJS references -->
<link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />
<script src="//Microsoft.WinJS.1.0/js/base.js"></script>
<script src="//Microsoft.WinJS.1.0/js/ui.js"></script>
<!-- BingMapsJSIntro references -->
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
<!-- Bing Maps references -->
<script type="text/javascript"
src="ms-appx:///Bing.Maps.JavaScript//js/veapicore.js"></script>
<!-- Our Bing Maps JavaScript Code -->
<script src="/js/bing.js"></script>
</head>
<body>
<div id="myMap"></div>
</body>
</html>
bing.js
var map;
function showMap(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var map = new Microsoft.Maps.Map($("mymap")[0],
{
credentials: "MYBINGMAPCODE",
center: new Microsoft.Maps.Location(latitude, longitude),
mapTypeId: Microsoft.Maps.MapTypeId.road,
zoom: 10
});
var center = map.getCenter();
var pin = new Microsoft.Maps.Pushpin(center, { width: 50, height: 50, draggable: false });
map.entities.push(pin);
}
//Initialization logic for loading the map control
(function () {
function initialize() {
Microsoft.Maps.loadModule('Microsoft.Maps.Map', { callback: GetMap });
}
document.addEventListener("DOMContentLoaded", initialize, false);
})();
Your modules callback method "GetMap" is non-existant in the code you provided.
Microsoft.Maps.loadModule('Microsoft.Maps.Map', { callback: GetMap });
You need something like...
function GetMap ()
{
var mapOptions = { credentials:"<Insert Your Bing Maps Key Here>" }
var map = new Microsoft.Maps.Map(document.getElementById("myMap"), mapOptions );
}

Google Fusion Map Info Window Not Formatted

I have created a Google Fusion Map with 2 layers. All appears to be working correctly with 1 exception.
I have formatted the Info Window of both layers using the Google Fusion Table tool. However, the Info Window on layer 1 is not appearing as specified with the code below. It works fine in the Google Fusion Table tool itself.
Can anyone spot what I've done wrong? Thanks.
<meta charset="UTF-8">
<title>Smithfield Foods UK</title>
<link rel="stylesheet" type="text/css" media="all" href="FusionMapTemplate.css" />
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
var defaultZoom = 10;
var defaultCenter = new google.maps.LatLng(52.6500, 1.2800)
var locationColumn = 'geometry'
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: defaultCenter,
zoom: defaultZoom,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infoWindow = new google.maps.InfoWindow();
// Initialize the first layer
var FirstLayer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1hpGzmMBg8bDgPOGrAXvc0_QVLSBqQ0O5vpLbfUE'
},
map: map,
styleId: 3,
templateID: 5,
suppressInfoWindows: true
});
google.maps.event.addListener(FirstLayer, 'click', function(e) {windowControl(e, infoWindow, map);
});
// Initialize the second layer
var SecondLayer = new google.maps.FusionTablesLayer({
query: {
select: 'PostCode',
from: '1RrCcRC-1vU0bfHQJTQWqToR-vllSsz9iKnI5WEk'
},
map: map,
styleId: 2,
templateId: 2,
suppressInfoWindows: true
});
google.maps.event.addListener(SecondLayer, 'click', function(e) {windowControl(e, infoWindow, map);
});
}
// Open the info window at the clicked location
function windowControl(e, infoWindow, map) {
infoWindow.setOptions({
content: e.infoWindowHtml,
position: e.latLng,
pixelOffset: e.pixelOffset
});
infoWindow.open(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
the issue:
templateID: 5,
//-------^
the D has to be lowercase

Resources