Google maps js api. Many maps on page - javascript

I have accordion (twitter-bootstrap), and on each I have a map.
Accordion blocks generates in foreach. Maps generates as partial view, that takes model with latitude and longitude and block id.
It calls in foreach:
#if (item.Latitude != null)
{
<p>Map:</p>
<div class="map-margin">
#{Html.RenderAction("Map", "Default", new {model = item});}
</div>
}
And action returns this partial view:
#model MPS.Administration.Models.ReportModel
<div id="map-canvas-#Model.Id.ToString()" style="width: 470px; height: 270px;"></div>
<script type="text/javascript">
$('#map-canvas-#Model.Id').ready(function() {
initialize();
});
function initialize() {
var lat = #Model.Latitude;
var lng = #Model.Longitude;
var latlng = new google.maps.LatLng(#Model.Latitude, #Model.Longitude);
debugger;
var mapOptions = {
center: latlng,
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var name = 'map-canvas-' + #Model.Id.ToString();
var map = new google.maps.Map(document.getElementById(name),mapOptions);
debugger;
// create a marker
var image = '../Content/Images/map_icon.png';
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: image
});
}
</script>
On layout I included script for js api.
Now I have 4 blocks, but only the last have map block (and it have only google logo and gray background without the map :( ). In debugger I see that lat and lng is same all 4 times. I think the problem is how I call initialize() map. Please help me to solve this issue.

The map si show only in the visible div. For the other you shuuld see only a grey background and in some case a small portion of the map in the upper left corner.
For see the map in every block you should use map.resize() or better use a genaration function for each time you show a new map. Initialize tipcally is call only when the windows is created and this this case the maps not visible fails

Related

Load Google Map in new window by appending a button

I'm trying to append a button to a page that when clicked will display my google map in a new page. I have a button that when clicked either gives an error or gives a blank page.
My code:
$('.content--body__wrapper').append('<button id="show-map" />')
$('.content--body__wrapper').append(`<script>
document.getElementById("show-map").addEventListener("click", function(){
var center = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: center
});
var marker = new google.maps.Marker({
position: center,
map: map,
});
})
</script>`);
$('.content--body__wrapper').append(`<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBcwtM8EBe7BE1NyPbU5SDYVYoBBtbtpTI&libraries=drawing" asyncdefer></script>`);
Error Code:
Edit: I took the callback out of the script source and I still don't get a page to load but I do have a lot less errors.
$('.content--body__wrapper').append('<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBcwtM8EBe7BE1NyPbU5SDYVYoBBtbtpTI&libraries=drawing&callback=initMap" async defer></script>');
In this line you say : when the API is loaded run the function called InitMap.
The problem is that this function is not definied in your js.
So remove this callback to use the documentReady event or remove documentReadyListener and create a function name initMap

HTML/JS - Google Maps v3 - select/remove marker by id from external link

I'm new to google maps and javascript . I'm trying to interact with the map using external links/lists.
My main problem is that i'm unable to select the marker on the map with its id.
I don't want to put all markers in a list/array and iterate over them since i don't know how many there will be at any point.
I simply want to select them by their id and work with them such as opening infowindow , removing them etc...
in my changeIcon() function , i tried some ways but none worked so far .
<html>
....
<div id="mapview"></div>
<a class="test-link" onmouseover="changeIcon()">Link</a>
<script>
function changeIcon()
{
//marker = map.selectMarker("4");
//marker = markers[4];
//infowindow.open(map,marker);
//$("#mapview").map.removeMarker(4);
}
var map = new google.maps.Map(document.getElementById('mapview'),
{
center: {lat: 44.540, lng: -78.546},
zoom: 16
});
function initMap()
{
var marker = new google.maps.Marker({
position: userPosition,
map: map,
id: 4
});
}
</script>
</html>
............................................
There is no API to get marker from map. ref:
"https://developers.google.com/maps/documentation/javascript/reference"
I think you dont want to use array because id will never match the index. So I suggest using dictionary:
var markers = {}; // "{}" to specify dictionary instead of "[]" to specify array
when you create marker, you add it to dictionary:
markers[4] = marker; // 4 is the id
when you want to get it:
var currentMarker = markers[4];

how to load vb.net variable to javascript

I'm trying to add google maps to my website, but instead of fixing a latitude and longitude for the location, I would like to be able to load the values from database. How do I get a variable from vb.net and pass it to javascript? I've tried:
<% Response.Write("<script>
function initialize() {
var myLatlng = new google.maps.LatLng(1.123456, 1.123456);
var mapOptions = {
zoom: 16,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'KH Automotive Location'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>")%>
and
new google.maps.LatLng(<%=latitude%>, <%=longitude%>);
Please help. Thanks
Sometimes, when I need to make absolutely sure (like with translated/localized strings) that the content comes across, I'll write it out to a hidden DIV somewhere on the page (or a hidden INPUT).
<div style='display:none' id='my_data'>stuffstuffstuff</div>
Then I just read the contents of the DIV (or INPUT, whatever I used). Slap a "runat=server" in it, and be able to write to it from your code-behind.
Should be able to write it in:
<% Response.Write("..
..
var myLatlng = new google.maps.LatLng(" & latitude & ", " & longitude & ");
..
")%>

How to set google map marker by latitude and longitude and provide information bubble

The following sample code provided by google maps api
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.77627, -73.910965);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
the following only shows google map of the location without a marker.
I was wondering how I can place a marker by giving latitude/longitude parameters?
And how is it possible to store my own information pulled from a database on that marker?
Here is a JSFiddle Demo that shows you how to set a google map marker by Lat Lng and also when click would give you an information window (bubble):
Here is our basic HTML with 3 hyperlinks when clicked adds a marker onto the map:
<div id="map_canvas"></div>
<a href='javascript:addMarker("usa")'>Click to Add U.S.A</a><br/>
<a href='javascript:addMarker("brasil")'>Click to Add Brasil</a><br/>
<a href='javascript:addMarker("argentina")'>Click to Add Argentina</a><br/>
First we set 2 global variables. one for map and another an array to hold our markers:
var map;
var markers = [];
This is our initialize to create a google map:
function initialize() {
var latlng = new google.maps.LatLng(40.77627, -73.910965);
var myOptions = {
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
We then create 3 lat lng locations where we would like to place our markers:
var usa = new google.maps.LatLng(37.09024, -95.712891);
var brasil = new google.maps.LatLng(-14.235004, -51.92528);
var argentina = new google.maps.LatLng(-38.416097, -63.616672);
Here we create a function to add our markers based on whatever is passed onto it. myloc will be either usa, brasil or argentina and we then create the marker based on the passed param. With in the addMarker function we check and make sure we don't create duplicate marker on the map by calling the for loop and if we the passed param has already been created then we return out of the function and do nothing, else we create the marker and push it onto the global markers array. After the marker is created we then attach an info window with it's associated marker by doing markers[markers.length-1]['infowin'] markers.length-1 is just basically getting the newly pushed marker on the array. Within the info window we set the content using html. This is basically the information you put into the bubble or info window (it can be weather information which you can populate using a weather API and etc). After info window is attached we then attach an onclick event listener using the Google Map API's addListener and when the marker is clicked we want to open the info window that is associated with it by calling this['infowin'].open(map, this) where the map is our global map and this is the marker we are currently associating the onclick event with.
function addMarker(myloc) {
var current;
if (myloc == 'usa') current = usa;
else if (myloc == 'brasil') current = brasil;
else if (myloc == 'argentina') current = argentina;
for (var i = 0; i < markers.length; i++)
if (current.lat() === markers[i].position.lat() && current.lng() === markers[i].position.lng()) return;
markers.push(new google.maps.Marker({
map: map,
position: current,
title: myloc
}));
markers[markers.length - 1]['infowin'] = new google.maps.InfoWindow({
content: '<div>This is a marker in ' + myloc + '</div>'
});
google.maps.event.addListener(markers[markers.length - 1], 'click', function() {
this['infowin'].open(map, this);
});
}
When all is done we basically attach window.onload event and call the initialize function:
window.onload = initialize;

Retrieve position of a google maps v3 marker to Qt in a desktop app with QtWebKit

I'm building a Qt app with Python where you can point and click at a (google) map and get the coordinates of the location. The map is shown through a QWebView loading a simple HTML page and the user can create markers by clicking. Screenshot of the widget after clicking on the map.
However, I'm having trouble to retrieve the just-clicked location coordinates back to Qt (so that I can use them as variables -- and, for example, show them in the QLineEdits on the topleft corner above, as current location of the marker).
This is the relevant part of the HTML file:
<script type="text/javascript">
var map;
function initialize() {
var local = new google.maps.LatLng(-23.4,-40.3);
var myOptions = {
zoom: 5,
center: local,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'rightclick', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
var clickedLocation = new google.maps.LatLng(location);
var marker = new google.maps.Marker({
position: location,
map: map
});
map.setCenter(location);
}
function dummyTxt() {
return 'This works.';
}
</script>
I've been trying with evaluateJavaScript, but was not able to retrieve the coordinates. I tried to created a function to access the position with marker.getPosition(), but with no luck. The dummy below works though..
newplace = QWebView.page().mainFrame().evaluateJavaScript(QString('dummyTxt()'))
>>> print newplace.toString()
This works.
Any suggestions on how to get the coordinates back to Qt?
Edit:
Here is the code that worked for me:
def update_geo(self):
# Capture coordinates of the last marker on the map.
mark = self.map.page().mainFrame().evaluateJavaScript('document.getElementById("markerlocation").value').toString()
# Convert string to list of floats, stripping parentheses.
marker = str(mark).strip('()').split(', ')
decimals = [float(c) for c in marker]
Full source in https://github.com/nelas/veliger/blob/master/veliger.py#L2374
I found a work around to make it work but I'm not pretty sure that it will be the right approach. Anyway, this is what I did:
Create a hidden input in the body section of your html document to save the position data of the marker:
<body>
(...)
<input id="locationData" type="hidden">
(...)
</body>
In the javascript code, save the position of the marker in the hidden input every time it's created:
function placeMarker(location) {
(...)
document.getElementById("locationData").value = marker.position;
(...)
}
In your Qt code, read the value of the hidden input with the instruction:
webView->page()->mainFrame()->findFirstElement("#locationData").evaluateJavaScript("this.value").toString();
I hope it helps!
Source: http://opendocs.net/qt/4.6/webkit-formextractor.html

Categories

Resources