map as div background - Google Maps API - javascript

I'm using for a while following javascript code to load google map as DIV background.
// When the window has finished loading create our google map below
google.maps.event.addDomListener(window, 'load', init);
function init() {
// Basic options for a simple Google Map
// For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
var mapOptions = {
// How zoomed in you want the map to start at (always required)
zoom: 15,
// The latitude and longitude to center the map (always required)
center: new google.maps.LatLng(54.549047, 18.443433), // New York
// How you would like to style the map.
// This is where you would paste any style found on Snazzy Maps.
styles: [ { featureType:"all", elementType:"all", stylers:[ { invert_lightness:true }, { saturation:10 }, { lightness:30 }, { gamma:0.5 }, { hue:"#1C705B" } ] } ]
};
// Get the HTML DOM element that will contain your map
// We are using a div with id="map" seen below in the <body>
var mapElement = document.getElementById('map');
// Create the Google Map using out element and options defined above
var map = new google.maps.Map(mapElement, mapOptions);
}
works perfectly. But when I've tried to load there a marker which will point to my location, it crashes. Any ideas what will be the proper placement of such? I assume this is the proper code (which doesn't work..):
var myLatlng = new google.maps.LatLng(54.549047, 18.443433);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
thanks for the help!

Related

Changing javascript in google maps doesn't update it?

I am trying to make an AJAX map Google map, where the place markers update but not the map.
I have an ajax setup with a settimeout function, which returns new javascript. When the new javascript is loaded into my HTML, the changes do not reflect on my google map.
When I go into the firefox inspector and try and manipulate the javascript, (to try and change marker GPS coordinates), nothing happens to the map, and the points are still the same. Why does that not affect the map?
I have looked at several links to try and help me, but none of them explain the logic behind the javascript.
My PHP script returns javascript in plain text. But when these get
added to the HTML, The google map does not change and looks like it
needs to be re initialized before it recognizes new javascript?
Can someone explain how I should update the javascript, so the map re-centers on the newest marker and places the newest marker without refreshing the page / re initializing the map?
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: {lat: -20.530637, lng: 46.450046}
});
// Create an array of alphabetical characters used to label the markers.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
var locations = [
new google.maps.LatLng("-21.530637,46.450046),
new google.maps.LatLng("-22.530637,46.450046),
]
</script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<div class="result"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function refresh_div() {
jQuery.ajax({
url:'content.php',
type:'POST',
success:function(results) {
locations=results;
jQuery(".result").html(results);
}
});
}
t = setInterval(refresh_div,5000);
</script>
My "content.php" file. returns more google maps LatLng markers in plain text.
so PHP output is:
new google.maps.LatLng("-23.530637,46.450046"),
new google.maps.LatLng("-24.530637,46.450046"),
new google.maps.LatLng("-25.530637,46.450046"),
new google.maps.LatLng("-26.530637,46.450046")
I would like to summary the behavior of your ajax map:
Initialize map (probably with a set of predefined locations)
Repeatedly call content.php to retrieve new update of markers
Draw new markers to your map
The problem is that your code that handles ajax result doesn't do any map manipulation. In fact, it has to update the variable locations with new location set. Then create new markers with updated list of locations, then call MarkerCluster to apply them.
I created a fiddle to demonstrate it: https://jsfiddle.net/anhhnt/paffzadz/1/
What I did is extract the marker creating part from initMap, so that it can be called multiple times after locations is updated.
function updateMarker () {
// Create an array of alphabetical characters used to label the markers.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
};
function initMap() {
window.map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: -28.024, lng: 140.887}
});
updateMarker(map);
};
var locations = [
{lat: -31.563910, lng: 147.154312},
{lat: -33.718234, lng: 150.363181},
{lat: -33.727111, lng: 150.371124}
]
function refresh_div() {
jQuery.ajax({
url:'/echo/json/',
type:'POST',
data: {
json: JSON.stringify([
{lat: -42.735258, lng: 147.438000},
{lat: -43.999792, lng: 170.463352}
])
},
success:function(results) {
locations.concat(results);
updateMarker();
}
});
}
t = setInterval(refresh_div,5000);
Hope it helps.
Perhaps you have simple syntax error in your code - missing closing double quote:
new google.maps.LatLng("-23.530637,46.450046"),
...
..or better - remove first double quote:
new google.maps.LatLng(-23.530637,46.450046),
...

My google places kml url javascript

i have a problem with my places from google maps, i already have a functionality map with a file kml in my https server, but i don't want to download and upload the map every time I make changes, not work for me only embed I need manipulated with API, so this is my code:
var map;
var src = 'MY_SERVER/points_vl.kmz';
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(20.63736, -105.22883),
zoom: 2,
});
loadKmlLayer(src, map);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = 'http://www.nearby.org.uk/google/circle.kml.php?radius=5miles&lat='+position.coords.latitude+'&long='+position.coords.longitude;
loadKmlLayer(circle, map);
map.setCenter(pos);
setTimeout(function(){
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Current Location'
});
infowindow.setPosition(pos);
}, 2000);
});
}
}
function loadKmlLayer(src, map) {
var kmlLayer = new google.maps.KmlLayer(src, {
suppressInfoWindows: true,
preserveViewport: false,
map: map
});
google.maps.event.addListener(kmlLayer, 'click', function(event) {
var content = event.featureData.infoWindowHtml;
var testimonial = document.getElementById('capture');
testimonial.innerHTML = content;
});
}
This work fine, but have a way for direct the kml from my url of google maps places?
Using an existant Google 'My Places' map with Maps API v3 styling this thread have some idea, but not work, if you get a idea how make it will make it wonderful
Go to your "MyMap" map. Click on the three dots next to the name of the map, click on "Export to KML":
Choose the "Keep data up to date with network link KML (only usable online):
Rename the .kmz file to .zip, then open it and open the doc.kml file it contains. That file will have the direct link to the KML data specifying your "MyMap".
Use that link in a google.maps.KmlLayer
proof of concept fiddle
original MyMap
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {
lat: 41.876,
lng: -87.624
}
});
var ctaLayer = new google.maps.KmlLayer({
url: 'https://www.google.com/maps/d/kml?mid=1-mpfnFjp1e5JJ1YkSBjE6ZX_d9w',
map: map
});
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<div id="map"></div>
<!-- add your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk">
</script>

Google Maps: Marker will not show up?

"use strict"; // eslint-disable-line
var map;
var initialLocation;
// TODO: Initialize and display Google Map
function initialize() {
//get current location
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
}
var mapProp = {
center:initialLocation,
zoom:6,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var marker = new google.maps.Marker({
position: initialLocation,
map: map
});
}
google.maps.event.addDomListener(window, 'load', initialize);
I am trying to set a marker to my current location using Javascript. When I load the map, however, while the map will center on my current location, no marker will appear?
Everything looks good, just add marker.setPosition(initialLocation); in the following section:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
marker.setPosition(initialLocation);// ****** missing line ******
map.setCenter(initialLocation);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
};
Here is a working JSFiddle with the necessary changes.
The key is from a Google MAP API sample and will need to be updated with your own, which you can obtain here: Google MAP API.
You may need to reload the JSFiddle example, as there appears to be an issue with the async defer coming from googleapis file. Wait a few seconds and press RUN.
Just make sure the content of variable initialLocation.
If it has the correct lon/lat, marker will appear.
You have to make sure it has correct value before the following:
var marker = new google.maps.Marker({
position: initialLocation,
map: map
});

Google custom Icon not loading

I am trying to load a custom icon for Google Maps API v3. The code I have is as follows:
$(function(){
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(42.2542586, -83.8873974),
zoom: 10
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
$('.valley').on('click', function(){
var myLatlng = new google.maps.LatLng(42.000, -83.0073974);
var mapOptions = {
zoom: 14,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var iconMarker = 'pin2.jpg'
var marker = new google.maps.Marker({
position: myLatlng,
animation: google.maps.Animation.DROP,
icon: iconMarker,
map: map,
title:"Hello"
});
});
});
The following script is in the 'application.html.erb' file (i've taken out my apikey)
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=APIKEY&sensor=false"></script>
Pretty straight forward and the actual map loads, but for some reason the rails app is not finding the .jpgfor the icon. I've placed it in various locations, currently it is in the root folder. For some reason it is trying to load the file as a text/html file instead of an image. I replaced the image with another image that is loading properly on the web page, and I still get a 404 with the browser trying to load it as an text/html
Here is the error in the console
Try with:
var iconMarker = '/assets/pin2.jpg';

Dropping marker with google maps api and javascript

Hi so I'm working a google maps element into an app I'm writing and am having trouble dropping a pin on the user's current location.
I can get the map to load a fusion table layer of pins, and center on the user's current location, but I'd like to be able to then drop a marker at the user's current location, and resize the map to fit all the markers. Is this possible? If not I can just set the zoom to an appropriate level.
This is the code I'm working with:
var geocoder = new google.maps.Geocoder();
function initialize() {
map = new google.maps.Map(document.getElementById('googft-mapCanvas'), {
center: new google.maps.LatLng([app:user-lat], [app:user-lon]),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
layer = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "col2, col0",
from: "1pbba_dFcpWQKQDXQUt9RNXp16GqX5Jz-NraafEI",
where: ""
},
options: {
styleId: 3,
templateId: 3
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
I should also say that the [app:user-lat] and [app:user-lon] calls are application specific, taking data from the mobile device, and will work to insert the current user's location. This is the reason I'm not doing a call for the current position through google maps api, thanks in advance for anyone taking the time to help.
To place a marker at the user's position, add this after you define your map:
var marker = new google.maps.Marker({
position: new google.maps.LatLng([app:user-lat], [app:user-lon]),
map: map
});
If you want to move it as the user moves, that will be a little more complicated, keep a reference to it and use marker.setPosition.
function initialize() {
map = new google.maps.Map(document.getElementById('googft-mapCanvas'), {
center: new google.maps.LatLng([app:user-lat], [app:user-lon]),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng([app:user-lat], [app:user-lon]),
map: map
});
layer = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "col2, col0",
from: "1pbba_dFcpWQKQDXQUt9RNXp16GqX5Jz-NraafEI",
where: ""
},
options: {
styleId: 3,
templateId: 3
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
To center the map on the markers (or zoom the map to show them all, you will need to query the FusionTable for all the markers, construct a google.maps.LatLngBounds object from their locations, then use that as an argument to map.fitBounds.
Here are a couple of examples that do that (but with a different column layout (two column location) than your table. The concept can be adjusted for your column layout (query for the single column location, parse it to create a google.maps.LatLng and add it to the google.maps.LatLngBounds):
http://www.geocodezip.com/v3_FusionTablesLayer_centerOnMarkers.html
http://www.geocodezip.com/www_vciregionmap_comC.html
example that zooms and centers the map on the data in your table. Notes:
The GViz API that is used is limited to 500 rows, if you have more data that that you probably don't want to do this anyway.
The maps is centered on the data not the user.

Categories

Resources