How to show google map in MVC? - asp.net-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>

Related

Why my razor page not show google map?

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.

InfoWindow contents spilling out using dynamic template?

Can anyone tell my why the contents of my InfoWindows are spilling out? When I view the InfoWindows in the Fusion Table UI, they all pop up and resize themselves correctly:
https://www.google.com/fusiontables/embedviz?q=select+col7+from+15wosKAeHC0gcpU_N6UPbxPL09RrEBKlQNEaCmnU&viz=MAP&h=false&lat=34.199813229302734&lng=-111.2955847411987&t=1&z=8&l=col7&y=2&tmplt=2
But when I try to use the html code to create a webpage, some (not all) of the InfoWindow contents spill out:
<!DOCTYPE html>
<html>
<head>
<title>CaveCreek - Google Fusion Tables</title>
<style type="text/css">
html, body, #googft-mapCanvas {
height: 300px;
margin: 0;
padding: 0;
width: 500px;
}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
google.maps.visualRefresh = true;
var map = new google.maps.Map(document.getElementById('googft-mapCanvas'), {
center: new google.maps.LatLng(34.199813229302734, -111.2955847411987),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('googft-legend'));
layer = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "col7",
from: "15wosKAeHC0gcpU_N6UPbxPL09RrEBKlQNEaCmnU",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googft-mapCanvas"></div>
</body>
</html>
My dynamic template InfoWindow code looks like:
{template .contents}
<div>
<div style="align: center">
<b>{$data.value.Stream}</b>
</div>
{if $data.value.y2012}
2012-{/if}
{if $data.value.y2012a}
2012a-{/if}
...
</div>
{/template}
I have tried to add height and width to the div tag for the InfoWindow in the template but that still doesn't seem to work.
Remove the visualRefresh, that is causing the infoWindow size to be calculated incorrectly.
google.maps.visualRefresh = true;
Note that the Google Maps visual refresh is going to be the default soon, so removing it is not a long-term solution.
If you set the height of the div and add overflow-y: scroll you should get a scrollbar on your content; does that not happen? One of the examples in the dynamic template help is setting the height differently based on fields being there or not, so that might help.

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 );
}

jQuery Mobile - Google navigation - Directions Service - Current position identification

I have a JQuery Mobile website that people use with their Android device.
(This website mainly deals with clients information.)
I've been looking to integrate a "GET DIRECTION" feature.
I was wondering if it's possible to open Google Navigation app (because it can be used as a GPS, voice navigation) with the current location and one client's address through JQM ?
If not, does anyone has any suggestion?
The official W3C site informs about the W3C Geolocation working group and the milestones that have been set.
You can find here a fresh (May 2012) W3C draft proposal for the Geolocation API.
Below you can find a sample working example that I created. The code finds the current position and provides a direction service. There is a textbox where you can write the target destination and a button which "Get Directions". When you click the button a list at the end of the page is filled with the directions.
You can modify it in order to fit your needs. Furthermore you can find more information about the directions service in the Google Map JavaScript API Directions Service.
<!doctype html>
<html lang="en">
<head>
<title>jQuery mobile with Google maps</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"> </script>
<script type="text/javascript">
var map;
var currentPosition;
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
function initialize(lat, lon)
{
currentPosition = new google.maps.LatLng(lat, lon);
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 15,
center: currentPosition,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
//directionsDisplay.setPanel($("#instructions-content"));
var currentPositionMarker = new google.maps.Marker({
position: currentPosition,
map: map,
title: "Current position"
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(currentPositionMarker, 'click', function() {
infowindow.setContent("Current position: latitude: " + lat +" longitude: " + lon);
infowindow.open(map, currentPositionMarker);
});
}
function locError(error)
{
alert("The position or the map could not be loaded.");
}
function locSuccess(position)
{
initialize(position.coords.latitude, position.coords.longitude);
}
$(document).ready(function()
{
navigator.geolocation.getCurrentPosition(locSuccess, locError);
$("#directions-button").click(function(){
var targetDestination = $("#target-dest").val();
if (currentPosition && currentPosition != '' && targetDestination && targetDestination != '')
{
var request = {
origin:currentPosition,
destination:targetDestination,
travelMode: google.maps.DirectionsTravelMode["DRIVING"]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setPanel(document.getElementById("instructions-content"));
directionsDisplay.setDirections(response);
// For debuging reasons uncomment
/*
var myRoute = response.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
alert(myRoute.steps[i].instructions);
}*/
}
});
}
else
{
alert("The target destination is empty or the current position could not be located.");
}
});
});
</script>
</head>
<body>
<div id="basic-map" data-role="page">
<div data-role="header">
<h1><a data-ajax="false" href="/">jQuery mobile with Google maps v3</a> examples</h1>
</div>
<div data-role="content">
<div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
<div id="map_canvas" style="height:350px;"></div>
</div>
<div data-role="fieldcontain">
<label for="name">Target Destination:</label>
<input type="text" name="target-dest" id="target-dest" value="" />
</div>
Get Directions
<div data-role="collapsible" id="instructions-container">
<h3>Instructions</h3>
<p><div id="instructions-content"></div></p>
</div>
</div>
</div>
</body>
</html>
Put the HTML code in a file map.html and open it directly with Mozilla Firefox (in case you don't want to put it on a server and test it). Otherwise put the file on a server and open it with any browser you want.
Initially you will be asked whether you want to share your current location. After you press the Share button you will see a map with a marker showing your current position. If you click the marker you will see you latitude and longitude.
I hope this helps.

YouTube video in a Google Map Info Window

I am trying to put a youtube video into a Google Map (v3) Info Window.
It works fine in Firefox and Internet Explorer.
It does not work in Safari and Chrome. In those browsers the positioning is off and the video doesn't move when you move the map. The video also gets chopped sometimes.
Here is the code that doe
<!doctype html>
<html>
<head>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
var map;
function initialize() {
latlng = new google.maps.LatLng(33.4222685, -111.8226402)
myOptions = {
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"),myOptions)
var point = new google.maps.LatLng(33.4222685, -111.8226402);
var marker = new google.maps.Marker({
position: point,
map: map
})
google.maps.event.addListener(marker, "click", function(){
bubble = new google.maps.InfoWindow({
content: '<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/UmFjNiiVk9w?fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/UmFjNiiVk9w?fs=1" type="application/x-shockwave-flash" width="425" height="344" allowscriptaccess="always" allowfullscreen="true"></embed></object>'
})
bubble.open(map, marker);
})
}
</script>
</head>
<body onload="initialize();">
<div id="map" style="width: 984px; height: 495px"></div>
</div>
</body>
</html>
An example of it working fine for the Google Maps API version 2 is here http://www.virtualvideomap.com/
Also on http://maps.google.com You can see youtube videos inside the Info Window working in Chrome and Safari by clicking "More..." on the top right of the map, and then checking "Videos".
This is a webkit bug, but you can find a solution here: http://groups.google.com/group/google-maps-js-api-v3/browse_thread/thread/ccaaee32b89e3656/c87bb19e4662bd78#c87bb19e4662bd78
Got a partial solution, use the iframe embed mode sorted the problem out to me!
Hope it helps!!
<!doctype html>
<html>
<head>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
var map;
function initialize() {
latlng = new google.maps.LatLng(33.4222685, -111.8226402)
myOptions = {
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"),myOptions)
var point = new google.maps.LatLng(33.4222685, -111.8226402);
var marker = new google.maps.Marker({
position: point,
map: map
})
google.maps.event.addListener(marker, "click", function(){
bubble = new google.maps.InfoWindow({
content: '<iframe title="YouTube video player" class="youtube-player" type="text/html" width="480" height="390" src="http://www.youtube.com/embed/UmFjNiiVk9w?rel=0" frameborder="0"></iframe>'
})
bubble.open(map, marker);
})
}
</script>
</head>
<body onload="initialize();">
<div id="map" style="width: 984px; height: 495px"></div>
</div>
</body>
</html>
I recently solved this problem by adding the style:
iframe { -webkit-transform:translate3d(0,0,0); }
to my css file. In my case all of the dynamic content was already inside an iFrame and I was still having this problem. I saw this transform suggestion somewhere awhile ago, but only just tried it today. I tested it in Chrome and Safari on Windows 7. There is still some position lag, but it basically works fine now.

Resources