Hi I am having trouble to pass a value from a code behind (onLoad) to javascript.
I am able to get the value for the address of the draggable marker(if INITIAL LAT and LONG value declared statically on javascript). Now I tried to load the value on ON Load value on Code behind using two hidden fields the problem is doesn't show the map and marker. Here's my code
<div class="panel-body">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyCPzl7Nmzd71jMSTi46X5tGxpLCuo2n1sy"></script>
<script type="text/javascript">
var markers = [
{
"title": 'Target Location',
//"lat": '43.7328831',
//"lng": '-79.6784712',
"lat": document.getElementById<%= HdLat.ClientID%>.value,
"lng": document.getElementById<%= HdLng.ClientID%>.value,
"description": ''
}
];
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var geocoder = geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
for (var i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title,
draggable: true,
animation: google.maps.Animation.DROP
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
google.maps.event.addListener(marker, "dragend", function (e) {
var lat, lng, address;
geocoder.geocode({ 'latLng': marker.getPosition() }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = marker.getPosition().lat();
lng = marker.getPosition().lng();
address = results[0].formatted_address;
document.getElementById("mytext").value = address;
}
});
});
})(marker, data);
latlngbounds.extend(marker.position);
}
var bounds = new google.maps.LatLngBounds();
map.setCenter(latlngbounds.getCenter());
//map.fitBounds(latlngbounds);
}
</script>
<div id="dvMap" style="width: 500px; height: 500px">
</div>
<br />
<div class="form-group"><asp:Label ID="Label1" runat="server"></asp:Label><br />
<input type="text" id="mytext" class="form-control" name="Address"/>
<asp:Button ID="Button1" runat="server" Text="Button" />
<%--<asp:ImageButton ID="ImageButton4" runat="server" class="popovers" AlternateText="Point Location" Height="28px" ImageAlign="AbsMiddle" ImageUrl="~/img/maploc.png" Width="28px" data-original-title="Locate" data-content="Locate by means of map " data-placement="right" data-trigger="hover" />--%>
<asp:HiddenField ID="HdLat" runat="server" />
<asp:HiddenField ID="HdLng" runat="server" />
</div>
Code behind is
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
HdLat.Value = "43.7328831"
HdLng.Value = "-79.6784712"
End Sub
Hoping for your kind Help...
Easiest way is to use Literal server control, and pass the value. It is kind of weird, but it works.
var markers = [{
...
"lat": <asp:Literal runat="server" ID="LatLiteral" />,
"lng": <asp:Literal runat="server" ID="LngLiteral" />
}];
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
LatLiteral.Text = "43.7328831"
LngLiteral.Text = "-79.6784712"
End Sub
Visual Studio
Notice that Visual Studio will complain for syntax error. You can ignore it.
Rendered Code
Related
I'm trying to get the Lng and Lat from the marker that I set on the google maps api.
I automatically want the coordinates to take place in my html form.
It looks like I'm not getting the getPosition() right, because every other variable I use (something like var x = 34) does work.
My code:
<form action="send_nieuwcontainer.php" method="post">
Marker_name: <input type="text" name="markername"><br>
Coördinaten: <br>
Lng: <input id="inputlng" type="text" placeholder="<?php $lng; ?>" readonly="readonly">
Lat: <input id="inputlat" type="text" placeholder="<?php $lat; ?>" readonly="readonly"><br>
</form>
</div>
<script>
function initMap() {
var groningen = {lat: 53.218883, lng: 6.566298};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: groningen
});
map.addListener('click', function(e) {
clearMarkers();
addMarker(e.latLng, map);
});
}
var markers = [];
var lng = marker.getPosition().lng();
var lat = marker.getPosition().lat();
document.getElementById('inputlng').value = lng;
document.getElementById('inputlat').value = lat;
// Adds a marker to the map.
function addMarker(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map
});
markers.push(marker);
if (marker = true) {
document.getElementById('replaceMe').style.display = 'none';
document.getElementById('replacement').style.visibility = 'visible';
} else {
alert ("Does not work");
}
}
Does someone see what I'm doing wrong or maybe something I'm forgetting?
Note: I've already tried looking on stackoverflow and googlemaps api guide. They keep telling me to use getPosition()
As #Turnip said, the marker var is declared with var inside addMarker, so it's only accessible inside addMarker.
Try declaring marker outside the function like var marker; and then, inside the function, instead of using var marker = ..., use marker = ....
I am trying to display a map, zoom into a zipcode, and then place Congressional District overlay onto map. The overlay is here: https://www.google.com/fusiontables/DataSource?snapid=S506424n-DY
I downloaded the KML link file, and saved it onto my local IIS server. However, the overlay never is drawn.
I also added the following mime types to my IIS Server:
.kml application/vnd.google-earth.kml+xml
.kmz application/vnd.google-earth.kmz
The kml file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<NetworkLink>
<name><![CDATA[2012 US Congressional Districts]]></name>
<Link>
<href>
https://www.google.com/fusiontables/exporttable?query=select+col5+from+1QlQxBF17RR-89NCYeBmw4kFzOT3mLENp60xXAJM&o=kmllink&g=col5</href>
</Link>
My HTML/javascript looks like:
<script src="http://maps.googleapis.com/maps/api/js" type="text/javascript"></script>
<script language="javascript">
var map;
var marker;
function showAddress() {
$("#divGoogleMap").css('display', '');
var mapProp = {
center: new google.maps.LatLng(51.508742, -0.120850),
zoom: 11,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("divGoogleMap"), mapProp);
myListener = google.maps.event.addListener(map, 'click', function (event) {
placeMarker(event.latLng);
});
google.maps.event.addListener(map, 'drag', function (event) {
placeMarker(event.latLng);
});
var zipCode = $("#txtZip").val();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': zipCode }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//Got result, center the map and put it out there
var pos = results[0].geometry.location;
saveLocation(pos);
map.setCenter(pos);
marker = new google.maps.Marker({
map: map,
draggable: true,
position: pos
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
var kmlUrl = '/DesktopModules/HelloWorld/2012_US_Congressional_Districts.kml';
var kmlOptions = {
suppressInfoWindows: true,
preserveViewport: false,
map: map
};
var kmlLayer = new google.maps.KmlLayer(kmlUrl, kmlOptions);
}
function placeMarker(location) {
if (marker) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map,
draggable: true
});
google.maps.event.addListener(marker, "drag", function (mEvent) {
populateInputs(mEvent.latLng);
});
}
saveLocation(location);
}
function saveLocation(pos) {
$("#hfLatitude").val(pos.lat());
$("#hfLogitude").val(pos.lng());
}
</script>
<table cellpadding="2" cellspacing="2" border="0">
<tr>
<td>
<asp:TextBox ID="txtZip" ClientIDMode="Static" runat="server"></asp:TextBox>
</td>
<td>
<input type="button" id="btnSearch" value="Search" onclick="showAddress()" />
</td>
</tr>
</table>
<div id="divGoogleMap" style="width: 800px;height: 600px;display: none;"></div>
<asp:HiddenField ID="hfLatitude" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="hfLongitude" ClientIDMode="Static" runat="server" />
What am I doing wrong here?
For use in google maps th kml must be located in an accessible server e not in local.
This is form google doc.
Overview
The Google Maps API supports the KML and GeoRSS data formats for
displaying geographic information. These data formats are displayed on
a map using a KmlLayer object, whose constructor takes the URL of a
publicly accessible KML or GeoRSS file.
the constructor take the URL of a publicly accessible KML.
Then for yoour need you must place your kml in a publicly accessible server
I had forgotten that i had already had a similar experience some years ago and the solution was precisely to place the files kml on a server accessible from the Internet.
Please consider the following codes:
In my .ascx:
<asp:Label ID="lblLat" runat="server" EnableViewState="false"></asp:Label>
<asp:Label ID="lblLng" runat="server" EnableViewState="false"></asp:Label>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var latlng = new google.maps.LatLng(5.4149253, 100.3407387);
var map = new google.maps.Map(document.getElementById('map'), {
center: latlng,
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function (event) {
marker.setPosition(event.latLng);
var yeri = event.latLng;
document.getElementById('lblLat').value = yeri.lat().toFixed(6);
document.getElementById('lblLng').value = yeri.lng().toFixed(6);
});
</script>
After dragging the marker around the map and submit,
In my .ascx.cs:
string lat = lblLat.Text;
string lng = lblLng.Text;
This 2 lines return null values. Can I please know what I've done wrong? It's just not getting the values from the Marker on the Map.
The label is converted into a span and the html elements like span or div does not have ViewState neither the text/html of these is sent to server side. The form elements that are submitted are the input elements, and hidden field is one of them. The asp.net maintains ViewState of the hidden fields. I am afraid you have to use hidden fields to maintain the value of label between postbacks.
In your .ascx:
<asp:Label ID="lblLat" runat="server" EnableViewState="false"></asp:Label>
<asp:Label ID="lblLng" runat="server" EnableViewState="false"></asp:Label>
<!-- 1. Add hidden fields to store and submit the latlng values -->
<asp:HiddenField id="lblLatHidden" runat="server" />
<asp:HiddenField id="lblLngHidden" runat="server" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var latlng = new google.maps.LatLng(5.4149253, 100.3407387);
var map = new google.maps.Map(document.getElementById('map'), {
center: latlng,
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function (event) {
marker.setPosition(event.latLng);
var yeri = event.latLng;
document.getElementById('lblLat').innerHtml = yeri.lat().toFixed(6);
document.getElementById('lblLng').innerHtml = yeri.lng().toFixed(6);
// 2. update the hidden fields via javascript
document.getElementById('lblLatHidden').value = yeri.lat().toFixed(6);
document.getElementById('lblLngHidden').value = yeri.lng().toFixed(6);
});
</script>
In my .ascx.cs:
string lat = lblLatHidden.Value;
string lng = lblLngHidden.Value;
Using ASP.net and WebForms i am trying to store the user's location (Latitude, Longitude) to a database. This presents the problem:
i want to get values of laqngitude and latude of google map by clicking Bbutton i got 0 values in database..
my database ha two filed langitude and latitude which has double datatype.
Here's the sample code of my first attempt:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var long = 0;
var lat = 0;
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(18.9300, 72.8200),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
google.maps.event.addListener(map, 'click', function (e) {
long = e.latLng.lng();
lat = e.latLng.lat();
document.getElementById("lat").value = lat;
document.getElementById("lng").value = long;
alert("Latitude: " + lat + "\r\nLongitude: " + long);
});
}
</script>
<form id="myForm" runat="server">
<div id="dvMap" style="width: 300px; height: 300px">
</div>
<asp:HiddenField ID="lat" runat="server" />
<asp:HiddenField ID="lng" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
</body>
And below is the .aspx code-behind file. We save the longitude and latitude to the database during the Click event of the button:
protected void Button1_Click(object sender, EventArgs e)
{
//TODO: Ask Stackoverflow how to get these values from browser-land javascript
Double latitude = Convert.ToDouble(lat.Value);
Double longitude = Convert.ToDouble(lng.Value);
SqlConnection con = new SqlConnection();
con.ConnectionString = "#Data Source=(LocalDB)\v11.0;AttachDbFilename=Database.mdf;Integrated Security=True";
string query1 = "insert into Courses(longi,lati) values (#lati, #longi)";
SqlCommand cmd1 = new SqlCommand(query1, con);
cmd1.Parameters.AddWithValue("#lati", latitude);
cmd1.Parameters.AddWithValue("#longi", longitude);
con.Open();
cmd1.ExecuteNonQuery();
con.Close();
}
You need to access the form being posted in your server side code. The Request.Form object to be more precise.
There is a NameValueCollection property on the form where you can lookup your posted form values with string key lookups
NameValueCollection nvc = Request.Form;
string lat,lng;
if (!string.IsNullOrEmpty(nvc["lat"])) {
lat = nvc["lat"];
}
if (!string.IsNullOrEmpty(nvc["lng"])) {
lng = nvc["lng"];
}
I'm using Ruby on Rails and don't have much knowledge in JavaScript(of course, my overall coding is so poor). I customized Google Maps API and wanted to make infowindow. However when I made my infowindow, 'sometimes' dropdown popped up in desktop(not in cell phone).
I think it's not only the Google Maps problem. I assumed that it can be any HTML, CSS related problem but no idea afterall..... It's very strange because dropdown only pops up when the restaurant's name is some kinds(two words or name with some number, but I can't recognize what is the exact cause and difference..)
# my_javascript.js
function googleMap() {
var geocoder = new google.maps.Geocoder();
var restAddr = document.getElementById('address').value;
var restName = document.getElementById("name").value;
geocoder.geocode( { 'address': restAddr}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var restLatLng = results[0].geometry.location
var mapOptions = {
zoom: 13,
center: restLatLng
};
var map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
var marker = new google.maps.Marker({
map: map,
position: restLatLng
});
var infoWindow = new google.maps.InfoWindow({
//maxWidth: 100, it didn't work
content: restName // **this part is the problem. When the restName is like "new york", "house 2"(some with one-digit(?)-number). but not when the restName is "new york stree" kind. **
});
infoWindow.open(map, marker);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
window.onload = googleMap
and this is my view file.
# app/views/home/page.html.erb
<%= #rest.addr %>
<p>changed</p>
<input type="hidden" id="address" value="<%= #rest.addr %>">
<input type="hidden" id="name" value="<%= #rest.name %>">
<div id="map-canvas"></div>
Can anyone help me with some suggestions? Any comments will be very helpful to me and make me learn more about programming. Thanks!!
You have to get the infowindow content in da DIV and style the div with css.
In your case do '<div class="scrollFix">'+restName+'</div>' und set the div properties to:
.scrollFix {
line-height: 1.35;
overflow: hidden;
white-space: nowrap;
}
here is an working example :
http://jsfiddle.net/veaz/7Zm8w/