Google Maps API V3 Markers Not Showing - google-maps-api-3

I have used Version 2 for quite some time and decided it was time to go to Version 3 as part of a major site update. I based all my code on "Mike Williams' tutorial The Basics - Part 3: Loading the data from an XML file translated to v3". After hours of fine-tuning I had it all working, including clustering and custom markers.
I was a very happy bunny and keen to show it off. Then to my disappointment I discovered that it didn't work in either IE or Firefox (I had been testing it in Chrome).
I'm well aware that Google Maps API is not an easy thing to work with, but is there any reason why I should get this behaviour with different browsers? The map can be seen by going to www.littlehotels.co.uk/new/ and clicking on "Map Search". The code is here:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Little Hotels of Spain - Google Map</title>
<meta name="description" content="Little Hotels provides maps showing the location of hotels, using Google Maps to create both a street/road map and a satellite image.">
<meta name="keywords" content="Little Hotels, Little Hotels of Spain, Spain, mainland spain, balearic, balearics, canary, canaries, small, hotel, hotels, map, google map, holiday, holidays">
<style type="text/css">
html { height: 100% }
body{ height: 100%; margin: 0; padding: 0; font-family: Arial, Helvetica, sans-serif; font-size:12px; color:#333333;}
a:link, a:visited, a:hover {color: #FF6600; text-decoration: none; font-weight: bold;}
h1{font-size: 16px; color: #2B8CB9; font-weight: bold;}
#content{padding: 0 5px 0; width: 640px;}
#map_canvas { height: 100% }
.verdana{font-family:Verdana, Arial, Helvetica, sans-serif; font-size: 9px; color: #666666;}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer_compiled.js"></script>
<script type="text/javascript" src="../js/downloadxml.js"></script>
<script type="text/javascript">
//<![CDATA[
var gmarkers = [];
// global "map" variable
var map = null;
var markerclusterer = null;
var image = new google.maps.MarkerImage('../images/hotel_icon.png',
new google.maps.Size(32, 37),
new google.maps.Point(0,0),
new google.maps.Point(16, 35));
var shadow = new google.maps.MarkerImage('../images/hotel_shadow.png',
new google.maps.Size(51, 37),
new google.maps.Point(0,0),
new google.maps.Point(16, 35));
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
icon: image,
shadow: shadow
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
// save the info we need to use later for the side_bar
gmarkers.push(marker);
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
function initialize() {
var lat = 0;
var lng = 0;
var zoomzoom = 0;
var query = location.search.substring(1);
var pairs = query.split("&");
for (var i=0; i<pairs.length; i++) {
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0,pos).toLowerCase();
var value = pairs[i].substring(pos+1).toLowerCase();
if (argname == "lat") {lat = parseFloat(value);}
if (argname == "lng") {lng = parseFloat(value);}
if (argname == "zoom") {zoomzoom = parseInt(value);}
}
var thisLatlng = new google.maps.LatLng(lat, lng);
var myOptions = {
center: thisLatlng,
zoom: zoomzoom,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
downloadUrl("php-to-xml.php", 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=markers[i].getAttribute("html");
var hotel=markers[i].getAttribute("hotel");
var marker = createMarker(point,hotel,html);
}
var clusterStyles = [
{
opt_textColor: '#5a7aba',
url: '../images/cluster_icon.png',
height: 40,
width: 40
}
];
var mcOptions = {gridSize: 35, maxZoom: 8, styles: clusterStyles};
markerCluster = new MarkerClusterer(map, gmarkers,mcOptions);
});
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(300,50)
});
//]]>
</script>
</head>
<body onload="initialize()">
<div id="content">
<h1>Little Hotels Map Search</h1>
<span class="verdana">Click on the icons for more information or use the Google controls to zoom, scroll, pan and change view.<br /><br /></span>
<table border=1 bordercolor="#666666">
<tr>
<td>
<div id="map_canvas" style="width: 640px; height: 450px"></div>
</td>
</tr>
</table>
<br />
</div>
</body>
</html>
Thanks for any advice anyone can offer.

I get the error in Firefox:
Error: not well-formed
Source File: http://www.littlehotels.co.uk/new/maps/php-to-xml.php
Line: 1, Column: 1722
Check with an XML validator.

The returned XML is not well-formed. It contains :
pretty "pueblos blancos"
you have to use " for the double-quotes or a CDATA-section.
Because of that you'll not be able to parse the returned data as XML

Dr Molle, this is the PHP script:
<?php
header('Content-Type: text/xml');
header('charset:UTF-8');
require_once('../Connections/MySQL_extranet.php');
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
$xmlStr=str_replace("ñ",'ñ',$xmlStr);
return $xmlStr;
}
mysql_select_db($database_MySQL_extranet, $MySQL_extranet);
// Select all the rows in the markers table
$query = "SELECT hid, hotel, lat, lng, picture, summary FROM ex_hotel WHERE country = 'spain'";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
// Start XML file, echo parent node
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo ' html="<img src="../images/' . $row['picture'] . '" align="left" height="108" width="155" style="margin-right:8px;"> <div style="width:320px"> <a href="' . 'http://www.littlehotels.co.uk/new/spain/' . $row['hid'] . '.php" target="_parent" >' . parseToXML($row['hotel']) . '</a> <br><span class="verdana"><br>'.parseToXML($row['summary']).'</span></div>"';
echo ' lat="' . $row['lat'] . '"';
echo ' lng="' . $row['lng'] . '"';
echo ' />';
}
// End XML file
echo '</markers>';
?>
The parsetoXML function is supposed to solve my original problem. It works on quotes but not on the ñ character. I have variously tried replacing ñ with ñ &0141; and n. None of them work. However, I've just settled for avoiding use of ñ at the moment. I'll come back to address this problem again when I have more time.
Many thanks for pointing me in the right direction.

've just been looking into the same issue. It seems the custom icon shadow feature is being dropped anyway.
"All shadows have been removed in the visual refresh. Any shadows specified programmatically will be ignored."
https://developers.google.com/maps/documentation/javascript/basics#VisualRefreshChanges

Related

Here Maps Marker plot with address

I have full address (Ex: 31, High Street, New York - 10001, United States of America), I need to plot this address as a marked on Here Maps. Can address be used to plot marker?
Please refer to the below steps to add a marker on your given address at here maps:
Step 1. Please refer to the below example makes a geocoding request and retrieve the latitude, longitude, and complete address details of 31, High Street, New York - 10001, United States of America based on free-form text input. A clickable marker is placed on the location found.
HTML Snippet:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes">
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Search for a Location based on an Address</title>
<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.1/mapsjs-ui.css" />
<link rel="stylesheet" type="text/css" href="demo.css" />
<link rel="stylesheet" type="text/css" href="styles.css" />
<link rel="stylesheet" type="text/css" href="../template.css" />
<script type="text/javascript" src='../test-credentials.js'></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-core.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-service.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-ui.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js"></script>
</head>
<body id="geocode">
<div class="page-header">
<h1>Search for a Location based on an Address</h1>
<p>Request a location using a free-form text input and display it on the map.</p>
</div>
<p>This example makes a geocoding request and retrieves the latitude, longitude and
complete address details of <b>31, High Street, New York - 10001, United States of America</b> based on a free-form
text input. A clickable marker is placed on the location found.</p>
<div id="map"></div>
<div id="panel"></div>
<h3>Code</h3>
<p>Access to the geocoding service is obtained from the <code>H.service.Platform</code>
by calling <code>getSearchService()</code>. The <code>geocode()</code> method is used
to find a location by passing in the relevant <code>q</code> parameter as defined in
Geocoding and Search API v7.
The styling and display of the response are under the developer's control.</p>
<script type="text/javascript" src='demo.js'></script>
</body>
</html>
Javascript Snippet:
/**
* Calculates and displays the address details of 31, High Street, New York - 10001, United States of America
* based on a free-form text
* A full list of available request parameters can be found in the Geocoder API documentation.
* see: http://developer.here.com/rest-apis/documentation/geocoder/topics/resource-geocode.html
* #param {H.service.Platform} platform A stub class to access HERE services
*/
function geocode(platform) {
var geocoder = platform.getSearchService(),
geocodingParameters = {
q: '31, High Street, New York - 10001, United States of America'
};
geocoder.geocode(
geocodingParameters,
onSuccess,
onError
);
}
/**
* This function will be called once the Geocoder REST API provides a response
* #param {Object} result A JSONP object representing the location(s) found.
*
* see: http://developer.here.com/rest-apis/documentation/geocoder/topics/resource-type-response-geocode.html
*/
function onSuccess(result) {
var locations = result.items;
/*
* The styling of the geocoding response on the map is entirely under the developer's control.
* A representative styling can be found in the full JS + HTML code of this example
* in the functions below:
*/
addLocationsToMap(locations);
addLocationsToPanel(locations);
// ... etc.
}
/**
* This function will be called if a communication error occurs during the JSON-P request
* #param {Object} error The error message received.
*/
function onError(error) {
alert('Can\'t reach the remote server');
}
/**
* Boilerplate map initialization code starts below:
*/
//Step 1: initialize communication with the platform
// In your own code, replace variable window.apikey with your own apikey
var platform = new H.service.Platform({
apikey: window.apikey
});
var defaultLayers = platform.createDefaultLayers();
//Step 2: initialize a map - this map is centered over New York
var map = new H.Map(document.getElementById('map'),
defaultLayers.vector.normal.map,{
center: {lat:41.033, lng:-73.7471},
zoom: 15,
pixelRatio: window.devicePixelRatio || 1
});
// add a resize listener to make sure that the map occupies the whole container
window.addEventListener('resize', () => map.getViewPort().resize());
var locationsContainer = document.getElementById('panel');
//Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Create the default UI components
var ui = H.ui.UI.createDefault(map, defaultLayers);
// Hold a reference to any infobubble opened
var bubble;
/**
* Opens/Closes a infobubble
* #param {H.geo.Point} position The location on the map.
* #param {String} text The contents of the infobubble.
*/
function openBubble(position, text){
if(!bubble){
bubble = new H.ui.InfoBubble(
position,
{content: text});
ui.addBubble(bubble);
} else {
bubble.setPosition(position);
bubble.setContent(text);
bubble.open();
}
}
/**
* Creates a series of list items for each location found, and adds it to the panel.
* #param {Object[]} locations An array of locations as received from the
* H.service.GeocodingService
*/
function addLocationsToPanel(locations){
var nodeOL = document.createElement('ul'),
i;
nodeOL.style.fontSize = 'small';
nodeOL.style.marginLeft ='5%';
nodeOL.style.marginRight ='5%';
for (i = 0; i < locations.length; i += 1) {
let location = locations[i];
var li = document.createElement('li'),
divLabel = document.createElement('div'),
address = location.address,
content = '<strong style="font-size: large;">' + address.label + '</strong></br>';
position = location.position;
content += '<strong>houseNumber:</strong> ' + address.houseNumber + '<br/>';
content += '<strong>street:</strong> ' + address.street + '<br/>';
content += '<strong>district:</strong> ' + address.district + '<br/>';
content += '<strong>city:</strong> ' + address.city + '<br/>';
content += '<strong>postalCode:</strong> ' + address.postalCode + '<br/>';
content += '<strong>county:</strong> ' + address.county + '<br/>';
content += '<strong>country:</strong> ' + address.countryName + '<br/>';
content += '<strong>position:</strong> ' +
Math.abs(position.lat.toFixed(4)) + ((position.lat > 0) ? 'N' : 'S') +
' ' + Math.abs(position.lng.toFixed(4)) + ((position.lng > 0) ? 'E' : 'W') + '<br/>';
divLabel.innerHTML = content;
li.appendChild(divLabel);
nodeOL.appendChild(li);
}
locationsContainer.appendChild(nodeOL);
}
/**
* Creates a series of H.map.Markers for each location found, and adds it to the map.
* #param {Object[]} locations An array of locations as received from the
* H.service.GeocodingService
*/
function addLocationsToMap(locations){
var group = new H.map.Group(),
position,
i;
// Add a marker for each location found
for (i = 0; i < locations.length; i += 1) {
let location = locations[i];
marker = new H.map.Marker(location.position);
marker.label = location.address.label;
group.addObject(marker);
}
group.addEventListener('tap', function (evt) {
map.setCenter(evt.target.getGeometry());
openBubble(
evt.target.getGeometry(), evt.target.label);
}, false);
// Add the locations group to the map
map.addObject(group);
map.setCenter(group.getBoundingBox().getCenter());
}
// Now use the map as required...
geocode(platform);
CSS Snippet:
#geocode #map {
display: block;
width: 95%;
margin-bottom: 3px;
height: 450px;
background: grey;
}
#geocode #panel {
display: block;
width: 95%;
min-height: 450px;
max-height: 450px;
border: 1px solid #e3e3e3;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.05);
box-shadow: inset 0 1px 1px rgba(0,0,0,.05);
}
**Refer to the documentation for more details: https://developer.here.com/documentation/examples/maps-js/services/geocode-a-location-from-address
Code: https://jsfiddle.net/gh/get/jquery/2.1.0/heremaps/maps-api-for-javascript-examples/tree/master/map-with-dom-marker**
Step 2: This example displays a movable map of New York with a single marker highlighting the location of High Street (41.8625°N, 87.6166°W), your home. Marker displays the letter C in the correct club colors. The marker is capable of receiving DOM (Document Object Model) events such as mouseenter, mouseleave etc. The marker will fade if the mouse pointer is placed over it.
HTML Snippet:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes">
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>DOM Marker</title>
<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.1/mapsjs-ui.css" />
<link rel="stylesheet" type="text/css" href="demo.css" />
<link rel="stylesheet" type="text/css" href="styles.css" />
<link rel="stylesheet" type="text/css" href="../template.css" />
<script type="text/javascript" src='../test-credentials.js'></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-core.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-service.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-ui.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js"></script>
</head>
<body id="markers-on-the-map">
<div class="page-header">
<h1>DOM Marker</h1>
<p>Display a marker that is capable of receiving DOM events</p>
</div>
<p>This example displays a movable map of <b>New York</b> with a single marker
highlighting the location of High Street <i>(41.033°N, 73.7471°W)</i>,
your home. Marker displays the letter C in the correct club colors.</p>
<p>The marker is capable of receiving DOM (Document Object Model) events such as <code>mouseenter</code>,
<code>mouseleave</code> etc. The marker will fade if the mouse pointer is placed over it.</p>
<div id="map"></div>
<h3>Code</h3>
<p>DOM markers are created by using the <code>H.map.DomMarker</code> class by providing a <code>H.map.DomIcon</code>.</p>
<script type="text/javascript" src='demo.js'></script>
</body>
</html>
Java Script Snippet:
/**
* Create a marker that is capable of receiving DOM events and add it
* to the map.
* #param {H.Map} map A HERE Map instance within the application
*/
function addDomMarker(map) {
var outerElement = document.createElement('div'),
innerElement = document.createElement('div');
outerElement.style.userSelect = 'none';
outerElement.style.webkitUserSelect = 'none';
outerElement.style.msUserSelect = 'none';
outerElement.style.mozUserSelect = 'none';
outerElement.style.cursor = 'default';
innerElement.style.color = 'red';
innerElement.style.backgroundColor = 'blue';
innerElement.style.border = '2px solid black';
innerElement.style.font = 'normal 12px arial';
innerElement.style.lineHeight = '12px'
innerElement.style.paddingTop = '2px';
innerElement.style.paddingLeft = '4px';
innerElement.style.width = '20px';
innerElement.style.height = '20px';
// add negative margin to inner element
// to move the anchor to center of the div
innerElement.style.marginTop = '-10px';
innerElement.style.marginLeft = '-10px';
outerElement.appendChild(innerElement);
// Add text to the DOM element
innerElement.innerHTML = 'C';
function changeOpacity(evt) {
evt.target.style.opacity = 0.6;
};
function changeOpacityToOne(evt) {
evt.target.style.opacity = 1;
};
//create dom icon and add/remove opacity listeners
var domIcon = new H.map.DomIcon(outerElement, {
// the function is called every time marker enters the viewport
onAttach: function(clonedElement, domIcon, domMarker) {
clonedElement.addEventListener('mouseover', changeOpacity);
clonedElement.addEventListener('mouseout', changeOpacityToOne);
},
// the function is called every time marker leaves the viewport
onDetach: function(clonedElement, domIcon, domMarker) {
clonedElement.removeEventListener('mouseover', changeOpacity);
clonedElement.removeEventListener('mouseout', changeOpacityToOne);
}
});
// Marker for Chicago Bears home
var bearsMarker = new H.map.DomMarker({lat: 41.033, lng: -73.7471}, {
icon: domIcon
});
map.addObject(bearsMarker);
}
/**
* Boilerplate map initialization code starts below:
*/
//Step 1: initialize communication with the platform
// In your own code, replace variable window.apikey with your own apikey
var platform = new H.service.Platform({
apikey: window.apikey
});
var defaultLayers = platform.createDefaultLayers();
//Step 2: initialize a map - this map is centered over Chicago.
var map = new H.Map(document.getElementById('map'),
defaultLayers.vector.normal.map,{
center: {lat:41.881944, lng:-87.627778},
zoom: 11,
pixelRatio: window.devicePixelRatio || 1
});
// add a resize listener to make sure that the map occupies the whole container
window.addEventListener('resize', () => map.getViewPort().resize());
//Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Now use the map as required...
addDomMarker(map);
CSS Snippet:
#map {
width: 95%;
height: 450px;
background: grey;
}
#panel {
width: 100%;
height: 400px;
}
**Refer DOM Marker document for more details: https://developer.here.com/documentation/examples/maps-js/markers/map-with-dom-marker
Code: https://jsfiddle.net/gh/get/jquery/2.1.0/heremaps/maps-api-for-javascript-examples/tree/master/map-with-dom-marker**
TC

take a screenshot of a web map

I am just starting out with javascript and I am trying to create an interactive web map....
I want to be able to position the map then press a button that will take a screenshot and save it to the computer.
Here is the code for my map.....
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Display a map on a webpage</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<link href="https://api.mapbox.com/mapbox-gl-js/v2.9.1/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.9.1/mapbox-gl.js"></script>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script>
mapboxgl.accessToken = '[TOKEN]';
const map = new mapboxgl.Map({
container: 'map', // container ID
style: 'mapbox://styles/charlie-enright/cl5b8bjil002y14o5u8xrssah', // style URL
center: [-4.369240916438415, 51.925803756014965], // starting position [lng, lat]
zoom: 8, // starting zoom
projection: 'globe' // display the map as a 3D globe
});
map.on('style.load', () => {
map.setFog({}); // Set the default atmosphere style
});
</script>
</body>
</html>
I have tried using html2canvas (https://codepen.io/samsammurphy/pen/VXdOPv) but the button seems to end up in a layer behind my map and I can not take a screenshot of the displayed map.
Any ideas how I could create a button that allows for a screenshot to be taken which saves to the computer will be greatly appreciated.
Thanks,
Here's an example of using map.getCanvas().toDataURL() and then injecting an img tag into the DOM. (This is not my example, I found it on this codepen by Sam Murphy https://codepen.io/samsammurphy/pen/VXdOPv)
$('button').click(function() {
var img = map.getCanvas().toDataURL();
var width = $('#screenshotPlaceholder').width()
var height = $('#screenshotPlaceholder').height()
var imgHTML = `<img src="${img}", width=${width}, height = ${height}/>`
$('#screenshotPlaceholder').empty();
$('#screenshotPlaceholder').append(imgHTML);
});
});
The codepen I found this on was not working due to an expired access token, so here's a fork that works if you want to try it out.
https://codepen.io/chriswhong/pen/YzapomG
Here's the code I use to take map screenshots using html2canvas
html2canvas(document.getElementById("map"), {useCORS:true}).then(canvas => {
var pseudolink = document.createElement('a');
pseudolink.download = 'myMapScreenshot.png';
pseudolink.href = canvas.toDataURL()
pseudolink.click();
})

Google maps appearing grey

I'm doing a soccer app using rails on this. The framework i'm using is bootstrap. For some reason when I load my page my google map is appearing grey. Please help me get the map to properly function. My plan is to get it to display the map and show markers of parks nearby you. Here is my code: Code
<div id="map"></div>
<script>
function initMap(){
// map options
var options = {
zoom:8,
center:{lat: 440.7203,lng:-73.8812}
}
// new map
var map = new google.maps.Map(document.getElementById('map'), options);
// add marker
var marker = new google.maps.Marker({
position: {
lat:40.6782,
lng:-73.9442
},
map:map
})
}
setTimeout(initMap, 10)
</script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAGMt_iOISz_BWdQJp0SlJfqoVwV_BHSvM">
</script>
<h1>Park.scss</h1>
#map{
height: 300px;
width: 100%;
}
Try using the style as per below:
#map * {
overflow:visible;
}

setCenter within "center" event callback

I want to keep the map center coordinates into some limits. For this I call the setCenter method inside my "center" related callback function:
map.addObserver("center", function (obj, key, newValue, oldValue) {
var limits = {minLat: 47.4136, minLon: 5.9845, maxLat: 54.8073, maxLon: 14.3671};
if (newValue.latitude < limits.minLat || newValue.longitude < limits.minLon ||
newValue.latitude > limits.maxLat || newValue.longitude > limits.maxLon) {
var newLatLon = {latitude: Math.max(Math.min(newValue.latitude, limits.maxLat), limits.minLat),
longitude: Math.max(Math.min(newValue.longitude, limits.maxLon), limits.minLon)};
map.setCenter(nokia.maps.geo.Coordinate.fromObject(newLatLon));
console.log(newValue);
console.log(map.center);
}
});
If I drag the map outside the limits, I see in the console the map.center being correctly adjusted, but the newValue coordinates keep being outisde the limits.
Did I misunderstand the API ?
I am using http://api.maps.nokia.com/2.2.3/jsl.js?with=all
Adding an observer to a property and then altering that property within the observer function is not guaranteed to work for all properties. My understanding is that re-setting the center is not supported in order to avoid infinite loops. You would be better off using the event framework rather than observers in this case.
The code below restricts the centre of the map to remain within a rectangle centred on Germany. If you drag the map it will stop dead, if you flick the map it will bounce back. You will need to obtain your own free app id and token to get it to work.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=7; IE=EmulateIE9" />
<title>Nokia Maps API Example: Restricted Area</title>
<!-- KML support is required here. -->
<script type="text/javascript" charset="UTF-8" src="http://api.maps.nokia.com/2.2.3/jsl.js"></script>
</head>
<style type="text/css">
html {
overflow:hidden;
}
body {
margin: 0;
padding: 0;
overflow: hidden;
width: 100%;
height: 100%;
position: absolute;
}
#mapContainer {
width: 80%;
height: 80%;
}
</style>
</head>
<body>
<div id="mapContainer"></div>
<script type="text/javascript">
/////////////////////////////////////////////////////////////////////////////////////
// Don't forget to set your API credentials
//
// Replace with your appId and token which you can obtain when you
// register on http://api.developer.nokia.com/
//
nokia.Settings.set( "appId", "APP ID");
nokia.Settings.set( "authenticationToken", "TOKEN");
//
/////////////////////////////////////////////////////////////////////////////////////
</script>
<div id="uiContainer"></div>
<script>
var mapContainer = document.getElementById("mapContainer");
var map = new nokia.maps.map.Display(mapContainer, {
center: [51, 7],
zoomLevel: 6
});
map.addComponent(new nokia.maps.map.component.Behavior());
var dragger = map.getComponentById("panning.Drag");
// Set of initial geo coordinates to create the purple polyline
var points = [
new nokia.maps.geo.Coordinate(47.4136, 5.9845),
new nokia.maps.geo.Coordinate(47.4136, 14.3671),
new nokia.maps.geo.Coordinate(54.8073, 14.3671),
new nokia.maps.geo.Coordinate(54.8073, 5.9845),
new nokia.maps.geo.Coordinate(47.4136, 5.9845)
];
// Transparent purple polyline
map.objects.add(new nokia.maps.map.Polyline(
points,
{
pen: {
strokeColor: "#22CA",
lineWidth: 5
}
}
));
var restrict = function(evt) {
var limits = {minLat: 47.4136, minLon: 5.9845, maxLat: 54.8073, maxLon: 14.3671};
if (map.center.latitude < limits.minLat || map.center.longitude < limits.minLon ||
map.center.latitude > limits.maxLat || map.center.longitude > limits.maxLon) {
var latitude = Math.max(Math.min(map.center.latitude, limits.maxLat), limits.minLat);
var longitude = Math.max(Math.min(map.center.longitude, limits.maxLon), limits.minLon);
map.setCenter(new nokia.maps.geo.Coordinate(latitude,longitude));
evt.cancel();
}
}
map.addListener("dragend", restrict);
map.addListener("drag", restrict);
map.addListener("mapviewchange", restrict);
map.addListener("mapviewchangeend", restrict);
map.addListener("mapviewchangestart", restrict);
</script>
</body>
</html>
I have added event listeners to five events here, dragend, drag, mapviewchange, mapviewchangeend and mapviewchangestart - depending upon the effect you require, you may not need them all. The line evt.cancel(); stops the event from being processed.

Google Maps Address Components Geocoding vs Places API - Short vs Long Name

Hey there GMaps API developers. To start - what an incredible product and service the Google Maps/JS API v3 is - thank you so much! Now, with that important bit of sincere gratitude out of the way...
The short_name vs long_name options for address components is a nice feature, but for each service these two attributes mostly contain the same values, except geocode has what I would expect for short_name for both and places has what I would expect for long_name for both! *tears*
Before Places library came out I just assumed that Google didn't actually have short/long versions for street name, localities, etc - but now it seems you do have that formatting somewhere - maybe different product teams have different databases?
So what's the deal?
Image of what I'm talking about (would embed but this is my first stackoverflow question so no reputation): http://i.imgur.com/XPVj8.png
Detailed list of how I wish this worked:
for routes, geocode's short_name places' long_name
have the same "types" value for locality/sublocality between geocode and places (either is fine, just pick one)
consistently provide short/long for state (administrative_area_level_1) - geocode gets this right but places doesn't
same for country - and where is geocode getting its "USA" in the formatted address?
would be neat if postal_code long_name had zip+4, but I would imagine that'd be a huge endeavor from a data standpoint
Thanks so much - looking forward to any insight on this behavior!
Code behind the image:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>GMaps API V3 Geocoder vs Places Address Components | Short vs Long Name</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true&libraries=places"></script>
<style type="text/css">
#map {height: 100px; width: 600px; border: 1px solid #333; margin-top: 0.6em; }
table { border-collapse: collapse; border-spacing: 0; }
table td {border-top: 1px solid #DDD; padding:4px 8px; }
</style>
<script type="text/javascript">
var map, geocoder, places, geocode_components, geocode_formatted, places_components, places_formatted
function initialize() {
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': '3 South Main Street, York New Salem, PA'},
function (results, status) {
geocode_components = results[0].address_components;
geocode_formatted = results[0].formatted_address;
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: results[0].geometry.location,
zoom: 10
});
places = new google.maps.places.PlacesService(map);
places.search({location: results[0].geometry.location, radius:100, keyword: "Pizza"},
function(results, status) {
//get details - this feels a little extraneous to me, but y'all know best
places.getDetails({reference: results[0].reference},
function(result, status) {
places_components = result.address_components;
places_formatted = result.formatted_address;
writeResults();
});
});
});
}
function writeResults() {
tbody = document.getElementById('results');
formatted = document.getElementById('formatted');
var rows = "";
for(var i=0; i<geocode_components.length; i++) {
var c = geocode_components[i];
rows = rows + '<tr><td>Geocoding</td><td>' + c.types[0] + '</td><td>' + c.short_name + '</td><td>' + c.long_name + '</td></tr>';
}
for(var i=0; i<places_components.length; i++) {
var c = places_components[i];
rows = rows + '<tr><td>Places</td><td>' + c.types[0] + '</td><td>' + c.short_name + '</td><td>' + c.long_name + '</td></tr>';
}
tbody.innerHTML = rows;
formatted.innerHTML = '<br />Geocode Formatted: ' + geocode_formatted + '<br />' + 'Places Formatted: ' + places_formatted;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
<table>
<thead><tr><th>Service</th><th>Type</th><th>Short Name</th><th>Long Name</th></tr></thead>
<tbody id="results"></tbody>
</table>
<div id="formatted"></div>
</body>
</html>
As noted in comments - this question (request) was fixed/implemented back in January, 2013, see https://issuetracker.google.com/issues/35821543

Resources