Google Map - Load KML Overlay - javascript

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.

Related

How to pass data from Code Behind to JavaScript?

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

Google Map marker not returning its value

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;

How can I draw google map using api v3 with multiple locations (address as well as zip codes)?

I am in a situation where I need to draw Google map using api v3 with multiple locations. These location can be static address string like "New Delhi, India" or 110005, but they will be several in numbers - can be comma separated or an array - i dont know exactly how they need to be put in the code. But simply i want to draw gmap with multiple locations, so a given map will have 9 or 10 location at once. How to do that? Can you please give me any working code on jsfiddle. For now my code to draw a gmap with only a single location (address only and not zip code) is given below -
JavaScript -
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
var marker;
function initialize()
{
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function codeAddress()
{
//var address = "Talwara Township, Punjab";
var address = document.getElementById("txtaddress").value;
geocoder.geocode({'address': address}, function(results, status){
if(status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var infowindow = new google.maps.InfoWindow({
content: "New Delhi, India"
});
infowindow.open(map, marker);
// Click the marker to Zoom to 9
google.maps.event.addListener(marker, 'click', function() {
map.setZoom(9);
map.setCenter(marker.getPosition());
});
}
});
}
</script>
HTML -
<body onLoad="initialize();codeAddress();">
<form method="get" action="">
<input type="text" id="txtaddress" name="txtaddress" size="30" value="New Delhi, India" />
<input type="submit" name="btnsubmit" value="Generate Map" />
</form>
<br /><br />
<div id="map_canvas" style="width:500px; height:380px; border:1px solid #AFAFAF;"></div>
</body>
What you are asking is Batch GeoCoding. The process of changing multiple addresses into a Geographical location is referred to as Batch GeoCoding.
Google Maps API is not directly supporting BatchGeocoding.
By using Google Maps API , We do geocode a single address at a time.
To acheive BatchGeoCoding, We need to iterate a list of Address.(Not too difficult I think)
For best Practice : GeoCode Example
BatchGeocode Reference :
The following are online batch Geocoding sites. Have it for reference.
Ref 1 , Ref 2
Working Demo
The Working demo is just a Proof of the Concept. It has to be refined in many ways. Please have a look at the reference to produce a better code.

Dynamically changing markers through local xml data

Am to get dynamically changing marker in google API through xml data, getting data from xml, si i have used set time interval to get dynamic effect...
something went wrong....
Please take look on below link and please suggest me:
jsBin link
Here is my complete code for your reference:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD_JQJz_Xyi5SP2IyMTzLQPjRz4l5Bh6FA&sensor=true">
</script>
</head>
<body>
<div id="map_canvas" style="width: 500px; height: 400px;"></div>
<script type="text/javascript">
var map = null;
function createMarker(latlng, html) {
var contentString = html;
var image = new google.maps.MarkerImage('http://www.google.com/mapfiles/markerA.png',
new google.maps.Size(20, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
var shadow = new google.maps.MarkerImage('http://www.google.com/mapfiles/shadow50.png',
new google.maps.Size(37, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
var marker = new google.maps.Marker({
position: latlng,
map: map,
shadow: shadow,
icon: image,
zIndex: 1
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
}
function initialize() {
var myOptions = {
zoom: 13,
center: new google.maps.LatLng(-18.432713,-70.317993),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
setInterval(function() {
downloadUrl("api.xml", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var html = "<strong>Taxi Arica</strong></br><strong>Latitud:</strong> " + markers[i].getAttribute("lat") + "</br><strong>Longitud:</strong> " + markers[i].getAttribute("lng");
var marker = createMarker(point,html);
}
});
},5000);
}
var infowindow = new google.maps.InfoWindow(
{size: new google.maps.Size(150,50)});
</script>
api.xml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<CATALOG>
<CD>
<marker>lat: "13.02378651", lng: "80.17517885"</marker>
</CD>
<CD>
<marker>lat: "13.06907", lng: "80.22546"</marker>
</CD>
<CD>
<marker>lat: "13.06105", lng: "80.25451"</marker>
</CD>
<CD>
<marker>lat: "13.05616", lng: "80.24248"</marker>
</CD>
</CATALOG>
Firstly: The Google Marker Options don't allow for a z-index attribute. Instead it should be called zIndex.
See the documentation:
https://developers.google.com/maps/documentation/javascript/reference#MarkerOptions
This should result in something like:
var marker = new google.maps.Marker({
position: latlng,
map: map,
shadow: shadow,
icon: image,
zIndex: 1
});
Secondly: you're trying to access the lat and lng values in your XML like so:
var lat = parseFloat(markers[i].getAttribute("lat"));
Your XML doesn't have any lat attribute on it like this:
<marker>lat: "13.02378651", lng: "80.17517885"</marker>
Instead your XML would need to look like this, for that javascript to work:
<marker lat="13.02378651" lng="80.17517885"></marker>
You probably need to go back to the drawing board and either rewrite your XML or work out a different way of parsing your XML. Right now you'd probably need to use a regular expression to isolate the lat and lng parts of this string lat: "13.02378651", lng: "80.17517885"
The best way would probably be to create new XML nodes for each of the lat and lng values, something like:
<marker>
<lat>13.02378651</lat>
<lng>80.17517885</lng>
</marker>
Or:
<marker>
<value name="lat">13.02378651</value>
<value name="lng">80.17517885</value>
</marker>

Display location Using Longitude/Latitude Coordinates - Google Maps

How can I input a set of coordinates and have Google maps show a location. This is all to be done through javascript (ie: no user interface)
Any help is appreciated
Note: If you already have a latitude/longitude, see Alteveer’s answer.
You'll need to need to use a geolocation service to get the latitude/longitude. Google Maps has one built in:
http://code.google.com/apis/maps/documentation/javascript/services.html#Geocoding
Here's an example of how to use it:
<!-- Placeholder for the Google Map -->
<div id="map" style="height: 512px;">
<noscript>
<!-- http://code.google.com/apis/maps/documentation/staticmaps/ -->
<img src="http://maps.google.com/maps/api/staticmap?center=1%20infinite%20loop%20cupertino%20ca%2095014&zoom=16&size=512x512&maptype=roadmap&sensor=false" />
</noscript>
</div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
// Define the address we want to map.
var address = "1 infinite loop cupertino ca 95014";
// Create a new Geocoder
var geocoder = new google.maps.Geocoder();
// Locate the address using the Geocoder.
geocoder.geocode( { "address": address }, function(results, status) {
// If the Geocoding was successful
if (status == google.maps.GeocoderStatus.OK) {
// Create a Google Map at the latitude/longitude returned by the Geocoder.
var myOptions = {
zoom: 16,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
// Add a marker at the address.
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
try {
console.error("Geocode was not successful for the following reason: " + status);
} catch(e) {}
}
});
</script>
You should be able to initialize the map with latitude/longitude as follows: https://developers.google.com/maps/documentation/javascript/tutorial#MapOptions

Categories