I have a specific requirement where i have to display only railway stations in the map rather than the whole map. How can this be achieved.?. Please find the below code that i have tried.
<html>
<head>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?libraries=drawing&sensor=true">
</script>
<script type="text/javascript">
function initialize() {
// init map
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var drawingManager = new google.maps.drawing.DrawingManager();
drawingManager.setMap(map);
// init directions service
var dirService = new google.maps.DirectionsService();
var dirRenderer = new google.maps.DirectionsRenderer({suppressMarkers: true});
dirRenderer.setMap(map);
// highlight a street
// highlight a street
var request = {
origin: '',
destination: '',
travelMode: google.maps.TravelMode.TRANSIT
};
dirService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
dirRenderer.setDirections(response);
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var transitMode = steps[j].travel_mode;
if (transitMode == "TRANSIT") {
var vehicle = steps[j].transit.line.vehicle.type;
if (vehicle == "HEAVY_RAIL") {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
// polyline.getPath().push(nextSegment[k]);
}
}
}
}
}
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
Any help will be much appreciated.. Thanks in advance..
I didn't understand what actually you want to do, but for this special kind of mapping you can rely on transit.js
It may be difficult,because:
Which is "Railway STATION"?, Platform?,Mark-on-rail?,Wickets?,Master'sRoom?,EntranceGate?
GoogleTransitService may show transfer by WALK via stair steps.
Related
We saw in a similar question that the Places API should return up to 5 results, but right now we are only able to get 1 result. We were following the tutorial to display museums in Sydney. Does anyone know how to display more than one result? The script for the Maps and Places API is below.
let map;
let service;
let infowindow;
function initMap() {
const sydney = new google.maps.LatLng(-33.867, 151.195);
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById("map"), {
center: sydney,
zoom: 15
});
const request = {
query: "Museum",
fields: ["name", "geometry"]
};
service = new google.maps.places.PlacesService(map);
service.findPlaceFromQuery(request, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (let i = 0; i < results.length; i++) {
createMarker(results[i]);
}
map.setCenter(results[0].geometry.location);
}
});
}
function createMarker(place) {
const marker = new google.maps.Marker({
map,
position: place.geometry.location
});
google.maps.event.addListener(marker, "click", () => {
infowindow.setContent(place.name);
infowindow.open(map);
});
}
From the documentation:
Find Place from Query takes a text input and returns a place.
(note the singular "a place")
To get multiple results use nearbySearch (or textSearch)
const sydney = new google.maps.LatLng(-33.867, 151.195);
var request = {
location: sydney ,
radius: '10000',
type: ['museum']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (let i = 0; i < results.length; i++) {
createMarker(results[i]);
}
map.setCenter(results[0].geometry.location);
}
});
proof of concept fiddle
code snippet:
"use strict";
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBIwzALxUPNbatRBj3Xi1Uhp0fFzwWNBkE&libraries=places">
let map;
let service;
let infowindow;
function initMap() {
const sydney = new google.maps.LatLng(-33.867, 151.195);
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById("map"), {
center: sydney,
zoom: 15
});
var request = {
location: sydney ,
radius: '10000',
type: ['museum']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log("places service returned "+results.length+" results");
document.getElementById('info').innerHTML = "places service returned "+results.length+" results";
for (let i = 0; i < results.length; i++) {
createMarker(results[i]);
}
map.setCenter(results[0].geometry.location);
}
});
}
function createMarker(place) {
const marker = new google.maps.Marker({
map,
position: place.geometry.location
});
google.maps.event.addListener(marker, "click", () => {
infowindow.setContent(place.name);
infowindow.open(map);
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 90%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Place Searches</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=places&v=weekly"
defer
></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="info"></div>
<div id="map"></div>
</body>
</html>
This is my code, When i am calling removeMarkers(), it's not removing the markers.
function receiver(data, textStatus, XMLHttpRequest) {
var json = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
var lat = json[i]["lat"];
var lng = json[i]["lng"];
// push object into features array
features.push({ position: new google.maps.LatLng(lat,lng) });
}
features.forEach(function(feature) {
var marker1 = new google.maps.Marker({
position: feature.position,
//icon: icons[feature.type].icon,
map: map
});
});
gmarkers.push(marker1);
}
function removeMarkers(){
for(i=0; i<gmarkers.length; i++){
gmarkers[i].setMap(null);
}
}
This is my full code. For displaying places(church) that which i saved in my database along the route from origin to destination. If i changed the origin and destination i want to remove old markers and displaying new markers without refreshing the page.
css
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
html
<div id="map" height="460px" width="100%"></div>
<input type="text" id="distance" value="3" size="2">
<input type="text" id="from" />to
<input type="text" id="to" />
<input type="submit" onClick="route()" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=api_ key&libraries=places"></script>
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/routeboxer/src/RouteBoxer.js" type="text/javascript"></script>
javascript
<script>
var map;
var marker;
var infowindow;
var messagewindow;
var boxpolys = null;
var directions = null;
var routeBoxer = null;
var distance = null; // km
var service = null;
var gmarkers = [];
var boxes = null;
var coordinates=null;
var features = [];
var gmarkers = [];
<?php
echo "
var lat={$lat};
var lng={$lng};
"
?>
function initialize() {
var location = {lat: 10.525956868983068, lng:76.21387481689453};
map = new google.maps.Map(document.getElementById('map'), {
center: location,
zoom: 13
});
service = new google.maps.places.PlacesService(map);
routeBoxer = new RouteBoxer();
directionService = new google.maps.DirectionsService();
directionsRenderer = new google.maps.DirectionsRenderer({
map: map
});
}
function route() {
removeMarkers()
clearBoxes();
distance = parseFloat(document.getElementById("distance").value) * 0.1;
var request = {
origin: document.getElementById("from").value,
destination: document.getElementById("to").value,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
directionService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(result);
var path = result.routes[0].overview_path;
boxes = routeBoxer.box(path, distance);
drawBoxes();
findPlaces(0);
} else {
alert("Directions query failed: " + status);
}
});
}
function drawBoxes() {
boxpolys = new Array(boxes.length);
for (var i = 0; i < boxes.length; i++) {
boxpolys[i] = new google.maps.Rectangle({
bounds: boxes[i],
fillOpacity: 0,
strokeOpacity: 1.0,
strokeColor: '#000000',
strokeWeight: 0,
map: map
});
}
}
function findPlaces(searchIndex) {
var request = {
bounds: boxes[searchIndex],
};
coordinates = boxes[searchIndex].toString().match(/[0-9]+\.[0-9]+/g);
$.ajax({
url:"http://localhost/church_finder/index.php/MapController/search_church",
type:'POST',
data:{coordinates:coordinates},
//dataType:'json',
success: receiver
});
if (status != google.maps.places.PlacesServiceStatus.OVER_QUERY_LIMIT) {
searchIndex++;
if (searchIndex < boxes.length)
findPlaces(searchIndex);
} else {
setTimeout("findPlaces(" + searchIndex + ")", 1000);
}
}
function clearBoxes() {
if (boxpolys != null) {
for (var i = 0; i < boxpolys.length; i++) {
boxpolys[i].setMap(null);
}
}
boxpolys = null;
}
function receiver(data, textStatus, XMLHttpRequest) {
var json = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
var lat = json[i]["lat"];
var lng = json[i]["lng"];
features.push({ position: new google.maps.LatLng(lat,lng) });
}
features.forEach(function(feature) {
var marker1 = new google.maps.Marker({
position: feature.position,
map: map
});
});
gmarkers.push(marker1);
}
function removeMarkers(){
for(i=0; i<gmarkers.length; i++){
gmarkers[i].setMap(null);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
enter image description here
function removeMarkers(){
features.length=0;
if (gmarkers != []) {
for(var i=0; i<gmarkers.length; i++){
gmarkers[i].setMap(null);
}
}
gmarkers =[];
}
Your app throws loads of errors in the console and this is just a temporary fix to what you are asking for:
change the origin and destination, I want to remove old markers and
displaying new markers without refreshing the page
call your initialize() function with a script tag in your HTML file. This is where you include your API key for the project:
<script defer async src="https://maps.googleapis.com/maps/api/js?
key=YOUR_KEY&callback=initialize">
Where is the map element passed in the map constructor?
Create a div element in your HTML to contain the map and add CSS style to it
#map {
height: 100%;
}
html, body {
margin: 0;
padding: 0;
height: 100%;
}
This is actually in the Google Maps API documentation;
Always set the map height explicitly to define the size of the div
element that contains the map.
Now into your JS code...
What are you using var service for? var service is firstly declared in the global scope with a null value and then assigned to a PlacesService constructor...but service is not defined simply because you have not included the places library in your script tag:
ADD PLACES LIBRARY IF YOU WANT TO USE PLACES API
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?
key=YOUR_API_KEY&_ADD_libraries=places_PLEASE_"></script>
Because var service cannot be run, just remove it (it actually does not do anything but adding lines in your code right now) along with the RouteBoxer()
REMOVE THESE LINES - THEY ARE USELESS RIGHT NOW
service = new google.maps.places.PlacesService(map);
routeBoxer = new RouteBoxer();
If you do this, without refreshing the page, you clear the markers for each subsequent requests. You get loads of errors still because you have both syntax and logic bugs in your app.
Get a BIN here
I am trying to adapt this Google Maps distance calculator to my needs, but am not overly familiar with plain Javascript, and only Jquery.
I am trying to modify one of the destination variables so that it pulls it from a text box instead.
Usually the line reads :
var destinationA = 'pe219px';
But I am trying to change it to the following, usually I would do this with a keyup function to update the value as the person types in jquery, but im not sure what im doing in plain javascript. This is what I have come up with so far, but it doesn't appear to do a lot :
function setValue() {
destinationA=parseInt(document.getElementById('deliverypostcode').value);
}
This is the example I am trying to modify
https://developers.google.com/maps/documentation/javascript/examples/distance-matrix
This is the whole code :
<!DOCTYPE html>
<html>
<head>
<title>Distance Matrix service</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas {
height: 100%;
width: 50%;
}
#content-pane {
float:right;
width:48%;
padding-left: 2%;
}
#outputDiv {
font-size: 11px;
}
</style>
<script>
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var origin1 = new google.maps.LatLng(53.003604, -0.532764);
var origin2 = 'pe219px';
function setValue() {
destinationA=parseInt(document.getElementById('deliverypostcode').value);
}
var destinationB = new google.maps.LatLng(53.003604, -0.532764);
var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';
function initialize() {
var opts = {
center: new google.maps.LatLng(53.003604, -0.532764),
zoom: 8
};
map = new google.maps.Map(document.getElementById('map-canvas'), opts);
geocoder = new google.maps.Geocoder();
}
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin1, origin2],
destinations: [destinationA, destinationB],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '';
deleteOverlays();
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
addMarker(destinations[j], true);
outputDiv.innerHTML += origins[i] + ' to ' + destinations[j]
+ ': ' + results[j].distance.text + '<br>';
}
}
}
}
function addMarker(location, isDestination) {
var icon;
if (isDestination) {
icon = destinationIcon;
} else {
icon = originIcon;
}
geocoder.geocode({'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
});
markersArray.push(marker);
} else {
alert('Geocode was not successful for the following reason: '
+ status);
}
});
}
function deleteOverlays() {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
markersArray = [];
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="content-pane">
<div id="inputs">
<form name="form1" method="post" action="">
<label for="deliverypostcode">Your Postcode</label>
<input type="text" name="deliverypostcode" id="deliverypostcode">
</form>
<p><button type="button" onclick="calculateDistances();">Calculate
distances</button></p>
</div>
<div id="outputDiv"></div>
</div>
<div id="map-canvas"></div>
</body>
</html>
Your function setValue is never called.
What if you delete it and just place the following line at the begining of calculateDistances ?
var destinationA= document.getElementById('deliverypostcode').value;
This works for me. Also, you don't need to parseInt your text input. Geocoding converts strings to a lat/long coordinates.
I need to pass two addresses to the following code to show the direction between them based on chosen transportation mode. Once user selects two cities from the Dropdown box in page 1, I am going to send them to the code (page 2) to show their locations and direction between them.
I have copied this sample code from Google.I am now trying to combine it with my code but do not know how.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Travel modes in directions</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<style type="text/css">
html, body {
height: 50%;
margin: 0;
padding: 0;
}
#map-canvas {
height: 200%;
width:25%;
}
#media print {
html, body {
height: auto;
}
#map-canvas {
height: 650px;
}
}
</style>
<script>
function GetLocation(add) {
var geocoder = new google.maps.Geocoder();
var address = add;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
var output = latitude + "," + longitude;
return output;
} else {
alert("Request failed.")
}
});
};
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var haight = new google.maps.LatLng(-37.81411, 144.96327999999999);
var oceanBeach = new google.maps.LatLng(-37.814107, 144.96327999999994);
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: haight
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var selectedMode = document.getElementById('mode').value;
var request = {
origin: haight,
destination: oceanBeach,
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
travelMode: google.maps.TravelMode[selectedMode]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="panel">
<b>Mode of Travel: </b>
<select id="mode" onchange="calcRoute();">
<option value="DRIVING">Driving</option>
<option value="WALKING">Walking</option>
<option value="BICYCLING">Bicycling</option>
<option value="TRANSIT">Transit</option>
</select>
<script>GetLocation("Los Angeles, USA");</script>
<script>GetLocation("Las Vegas, USA");</script>
</div>
<div id="map-canvas"></div>
</body>
</html>
You are essentially asking about SearchBox . You don't need it though. You can directly take a form and get the submitted values and Geocode it to be passed in the aforementioned script.
If you want to pass the two addresses to the 2nd page in the query string, you can do something like this:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Travel modes in directions</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<style type="text/css">
html, body {
margin: 0;
padding: 0;
}
#map-canvas {
height: 500px;
width:600px;
}
</style>
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var origin = "Los Angeles, USA";
var destination = "Las Vegas, USA";
var maptype = google.maps.MapTypeId.ROADMAP;
var travelMode = google.maps.TravelMode.DRIVING;
var arrivalTime = null;
var departureTime = null;
function initialize() {
// If there are any parameters at eh end of the URL, they will be in location.search
// looking something like "?marker=3"
// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i=0; i<pairs.length; i++) {
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0,pos).toLowerCase();
var value = pairs[i].substring(pos+1).toLowerCase();
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "origin") {origin = unescape(value);}
if (argname == "dest") {destination = unescape(value);}
if (argname == "type") {
if (value == "m") {maptype = google.maps.MapTypeId.ROADMAP;}
if (value == "k") {maptype = google.maps.MapTypeId.SATELLITE;}
if (value == "h") {maptype = google.maps.MapTypeId.HYBRID;}
if (value == "t") {maptype = google.maps.MapTypeId.TERRAIN;}
}
if (argname == "mode") {
if (value == "driving") {travelMode = google.maps.TravelMode.DRIVING; }
if (value == "walking") {travelMode = google.maps.TravelMode.WALKING; }
if (value == "transit") {travelMode = google.maps.TravelMode.TRANSIT; }
if (value == "bicycling") {travelMode = google.maps.TravelMode.BICYCLING; }
}
if (argname == "arrive") {
arrivalTime = new Date(value);
}
if (argname == "depart") {
departureTime = new Date(value);
}
}
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('panel'));
calcRoute(origin, destination, travelMode, departureTime, arrivalTime);
}
function calcRoute(origin, destination, mode, departureTime, arrivalTime) {
var request = {
origin: origin,
destination: destination,
travelMode: mode,
};
if (travelMode == google.maps.TravelMode.TRANSIT)
request.transitOptions = {};
if (travelMode == google.maps.TravelMode.TRANSIT && !!departureTime)
request.transitOptions.departureTime = departureTime;
if (travelMode == google.maps.TravelMode.TRANSIT && !!arrivalTime)
request.transitOptions.departureTime = departureTime;
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else alert("Directions Request failed: "+status);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div id="panel"></div>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-162157-1";
urchinTracker();
</script>
</body>
</html>
working example
and working example with form input
To start off I'm fairly new to Javascript and the Google Maps API so any help will be greatly appreciated.
I'm building a map with polygons to mark boundary locations and the ability to search an address to see what polygon the address is in. The code works for both Firefox and Chrome, but for some reason when I try to search an address in IE, the map just reloads rather than placing the marker at the appropriate location.
I've included all the functions I use. The microajax Javascript function is used to read the xml file that contains the coordinates of all the polygon shapes. Since the polygons are being rendered in IE, I dont believe this is the cause of the problem so I didnt include it. I'm at a loss for what the problem could be. Thanks in advance.
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="microajax.js"></script>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 30px; padding: 0px }
#map_canvas { height: 100% }
</style>
<div id="map_canvas" style="width:800px; height:600px" text="If map is not present, this browser does not support Google Maps"></div>
<div id="message"></div>
<form onsubmit="showAddress()" action="#">
<input id="search" size="60" type="text" value="" />
<input type="submit" value="Go!" />
<input type="button" onclick="clearmarkers();" value="Clear markers" />
</form>
</head>
<body onload="initialize()">
<noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b>
However, it seems JavaScript is either disabled or not supported by your browser.
To view Google Maps, enable JavaScript by changing your browser options, and then
try again.
</noscript>
<script type="text/javascript">
var gmarkers = [];
var polys = [];
var labels = [];
var glob;
var geo = new google.maps.Geocoder();
var map;
function initialize() {
var ontario = new google.maps.LatLng(50.397, -85.644);
var myOptions = {
zoom: 5,
center: ontario,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
microAjax("xmloutput2.xml", function(data) {
// ========= processing the polylines ===========
var xmlDoc = xmlParse(data)
var lhins = xmlDoc.documentElement.getElementsByTagName("lhin");
// read each line
for (var a = 0; a < lhins.length; a++) {
var label = lhins[a].getAttribute("name");
var colour = lhins[a].getAttribute("colour");
// read each point on that line
var points = lhins[a].getElementsByTagName("point");
var pts = [];
for (var i = 0; i < points.length; i++) {
pts[i] = new google.maps.LatLng(parseFloat(points[i].getAttribute("lat")), parseFloat(points[i].getAttribute("lng")));
}
var poly = new google.maps.Polygon({
paths:pts,
strokeColor:"#000000",
strokeOpacity: 1,
strokeWeight: 2,
fillColor: colour,
fillOpacity: 0
});
poly.setMap(map);
polys.push(poly);
labels.push(label);
}
function showAddress() {
var search = document.getElementById("search").value;
geo.geocode( { 'address': search}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// How many results were found
document.getElementById("message").innerHTML = "Found " +results.length +" results";
// Loop through the results, placing markers
for (var i=0; i<results.length; i++) {
var marker = new google.maps.Marker({
map: map,
position: results[i].geometry.location
});
gmarkers.push(marker);
glob=checkpoint(marker);
if (glob == 99) {
var infowindowoptions = {
content: 'This address is not within a LHIN boundary'
}
infowindow = new google.maps.InfoWindow(infowindowoptions);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, this);
});
document.getElementById("message").innerHTML += "<br>"+(i+1)+": "+ results[i].formatted_address +" "+ results[i].geometry.location + "Outside of Bounds";
}
else {
var infowindowoptions = {
content: 'This address is in LHIN '+labels[glob]
}
infowindow = new google.maps.InfoWindow(infowindowoptions);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, this);
});
document.getElementById("message").innerHTML += "<br>"+(i+1)+": "+ results[i].formatted_address +" "+ results[i].geometry.location +
" - LHIN "+(glob+1)+" "+labels[glob];
}
}
map.setCenter(results[0].geometry.location);
map.setZoom(17)
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function clearmarkers() {
if (gmarkers) {
for (i in gmarkers) {
gmarkers[i].setMap(null);
}
gmarkers.length = 0;
}
}
function checkpoint(marker) {
var LNum;
var point = marker.getPosition();
for (var i=0; i<polys.length; i++) {
if (polys[i].containsLatLng(point)) {
Lnum = i;
i = 999; // Jump out of loop
}
else {
Lnum = 99
}
}
return Lnum
};
// Polygon getBounds extension - google-maps-extensions
// http://code.google.com/p/google-maps-extensions/source/browse/google.maps.Polygon.getBounds.js
if (!google.maps.Polygon.prototype.getBounds) {
google.maps.Polygon.prototype.getBounds = function(latLng) {
var bounds = new google.maps.LatLngBounds();
var paths = this.getPaths();
var path;
for (var p = 0; p < paths.getLength(); p++) {
path = paths.getAt(p);
for (var i = 0; i < path.getLength(); i++) {
bounds.extend(path.getAt(i));
}
}
return bounds;
}
}
// Polygon containsLatLng - method to determine if a latLng is within a polygon
google.maps.Polygon.prototype.containsLatLng = function(latLng) {
// Exclude points outside of bounds as there is no way they are in the poly
var bounds = this.getBounds();
if(bounds != null && !bounds.contains(latLng)) {
return false;
}
// Raycast point in polygon method
var inPoly = false;
var numPaths = this.getPaths().getLength();
for(var p = 0; p < numPaths; p++) {
var path = this.getPaths().getAt(p);
var numPoints = path.getLength();
var j = numPoints-1;
for(var i=0; i < numPoints; i++) {
var vertex1 = path.getAt(i);
var vertex2 = path.getAt(j);
if (vertex1.lng() < latLng.lng() && vertex2.lng() >= latLng.lng() || vertex2.lng() < latLng.lng() && vertex1.lng() >= latLng.lng()) {
if (vertex1.lat() + (latLng.lng() - vertex1.lng()) / (vertex2.lng() - vertex1.lng()) * (vertex2.lat() - vertex1.lat()) < latLng.lat()) {
inPoly = !inPoly;
}
}
j = i;
}
}
return inPoly;
}
Try getting rid of the form and instead set the onClick of the 'Go!' button to showAddress(). I tested this in IE7, Chrome, and Firefox and it worked.
You may want to try using jQuery to run your initialization code and for ajax. Instead of using body.onload, use this:
$(function(){
initialize();
}) ;
And for ajax:
$.ajax({
url: "xmloutput2.xml",
success: function(data){
// handle result
}
});
If the problem is that your form is submitting to the server and causing a page reload, you need to return false from the showAddress() function, and use onsubmit="return showAddress();":
<form onsubmit="return showAddress();" action="#">
<input id="search" size="60" type="text" value="" />
<input type="submit" value="Go!" />
<input type="button" onclick="clearmarkers();" value="Clear markers" />
</form>
...
function showAddress () {
....
return false ;
}
Try specifying version
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.19"></script>
Your getting the experimental version if you do not specify a version. I found the experimental version has problems with IE11