Google Place Autocomplete API Showing Blank Map - javascript

I'm using the following script to show auto complete place API on my webpage, everything is working fine but map is not showing, i have tried multiple solutions but they won't help in any way here is my script
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places"></script>
<script>
var map;
var marker;
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos,
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerAddress(str) {
document.getElementById("location-text-box").value = str;
}
function initialize() {
var mapOptions = {
zoom: 8
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Get GEOLOCATION
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
map.setCenter(pos);
marker = new google.maps.Marker({
position: pos,
map: map,
draggable: true
});
google.maps.event.addListener(marker, 'dragstart', function() {
//updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
//updateMarkerStatus('Dragging...');
//updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
// alert("drag ended");
//updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
map.setCenter(options.position);
marker = new google.maps.Marker({
position: options.position,
map: map,
draggable: true
});
// Update current position info.
google.maps.event.addListener(marker, 'dragstart', function() {
//updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
//updateMarkerStatus('Dragging...');
//updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
// alert("drag ended");
//updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
}
// get places auto-complete when user type in location-text-box
var input = /** #type {HTMLInputElement} */
(
document.getElementById('location-text-box'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29),
draggable: true
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon( /** #type {google.maps.Icon} */ ({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''), (place.address_components[1] && place.address_components[1].short_name || ''), (place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
out put i'm getting is
html
<div style="width:100%; height:100%;">
<input id="location-text-box"/>
<div id="map-canvas"></div>
</div>

Related

After maximize google map window, autocomplete doesn't work

I'm trying to use google map with mvc in my project.
I can find the location by typing in textbox while map is minimized.
The location is showed automatically.
However the location isn't showed automatically in the maximize state.
Here is my code :
function initialize() {
var latlng = new google.maps.LatLng(Lat, Long);
var map = new google.maps.Map(document.getElementById('map'), {
center: latlng,
zoom: 13
});
var marker = new google.maps.Marker({
map: map,
position: latlng,
draggable: true,
anchorPoint: new google.maps.Point(0, -29)
});
var input = document.getElementById('searchInput');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var geocoder = new google.maps.Geocoder();
var autocomplete = new google.maps.places.Autocomplete(input);
//Set initial restrict countries.
autocomplete.setComponentRestrictions(
{ 'country': ['mm'] });
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
autocomplete.addListener('place_changed', function () {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
infowindow.setContent(place.formatted_address);
infowindow.open(map, marker);
});
// this function will work on marker move event into map
google.maps.event.addListener(marker, 'dragend', function () {
geocoder.geocode({ 'latLng': marker.getPosition() }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Screenshot :
Screenshot 1
Screenshot 2
Set a z-index for .pac-container that is above the map (warning undocumented behavior, may change with future releases of the API)
.pac-container {
z-index: 2147483648;
}
proof of concept fiddle
code snippet:
function initialize() {
var latlng = new google.maps.LatLng(21.958828, 96.089103);
var map = new google.maps.Map(document.getElementById('map'), {
center: latlng,
zoom: 13
});
var marker = new google.maps.Marker({
map: map,
position: latlng,
draggable: true,
anchorPoint: new google.maps.Point(0, -29)
});
var input = document.getElementById('searchInput');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var geocoder = new google.maps.Geocoder();
var autocomplete = new google.maps.places.Autocomplete(input);
//Set initial restrict countries.
autocomplete.setComponentRestrictions({
'country': ['mm']
});
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
infowindow.setContent(place.formatted_address);
infowindow.open(map, marker);
});
// this function will work on marker move event into map
google.maps.event.addListener(marker, 'dragend', function() {
geocoder.geocode({
'latLng': marker.getPosition()
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px;
z-index: 0;
}
#searchInput {
top: 15px;
left: 120px;
}
.pac-container {
z-index: 2147483648;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<input id="searchInput" />
<div id="map"></div>

JavaScript GoogleMaps move placemarker

I'm using the following JavaScript to load GoogleMaps and center on London. The user can then move the map and place a marker for which I save the longitude and latitude. The code works fine for this.
$(document).ready(function() {
var myLatLng = {lat: 51.5073509, lng: -0.12775829999998223};
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(myLatLng),
zoom: 13
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var input = /** #type {HTMLInputElement} */(
document.getElementById('pac-input'));
var types = document.getElementById('type-selector');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
draggable: true,
map: map,
anchorPoint: new google.maps.Point(myLatLng)
});
google.maps.event.addListener(marker, "mouseup", function(event) {
$('#id_latitude').val(this.position.lat());
$('#id_longitude').val(this.position.lng());
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
marker.setIcon(/** #type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
$('#id_latitude').val(place.geometry.location.lat());
$('#id_longitude').val(place.geometry.location.lng());
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
}
if ($('#map-canvas').length != 0) {
google.maps.event.addDomListener(window, 'load', initialize);
}
});
I want to amend the code so that when I reload the user's information it automatically goes to the marker they set and they can move it to another location. I cannot work out how to do this. Please help.
First of all, for changing the marker's position, you should keep the marker object as a global variable after you create it so that you could edit it somewhere else outside the initialize function.
And after you have reload the user's information, you can change the position of the marker this way:
var latlng = new google.maps.LatLng(-24.397, 140.644); // new latlng here.
marker.setPosition(latlng); // marker is what you keeped global.
I don't know anything about the Django framework, if it supports callbacks or something like this, do the change work there.
var markerGlobal;
function initMap() {
var myLatLng = {
lat: -25.363,
lng: 131.044
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
draggable: true,
map: map,
title: 'Hello World!'
});
markerGlobal = marker;
}
function changeMarkerPosition() {
var newLatlng = new google.maps.LatLng(-24.397, 131.084);
markerGlobal.setPosition(newLatlng);
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
</head>
<body>
<div>
<button onclick="changeMarkerPosition()">Click me!</button>
</div>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
</body>
</html>

Autocompletion en show on map

I have tried to make autocompletion for my application and show this to my Google maps but it doesn't works well.
The code is in a seperate js file called autocomplete.js
I already have a google maps in app so I want to use the same.
The id of google map is: googleMap
The id of search button is: autosearch
The id of input is: autoinput
"use strict";
var input = document.getElementById('autoinput');
var options = {
bounds: defaultBounds,
types: ['establishment']
};
autocomplete = new google.maps.places.Autocomplete(input, options);
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
var input = document.getElementById('autoinput');
var options = {
types: ['(cities)'],
componentRestrictions: {country: 'be'}
};
function fillInAddress() {
var place = autocomplete.getPlace();
var defaultBounds = document.getElementById('googleMap')(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
var input = document.getElementById('autoinput');
var searchBox = new google.maps.places.SearchBox(input, {
bounds: defaultBounds
});
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
};
I changed code etc but i guess i deleted something that i need.
This is the other js file for geolocation called locationSearch.js:
var google;
$( document ).ready(function() {
zoekLocatie();
});
function zoekLocatie() {
var output = document.getElementById("googleMap");
navigator.geolocation.getCurrentPosition(success, error);
output.innerHTML = "<p>Looking for your location...</p>";
if (!navigator.geolocation) {
output.innerHTML = "<p>Your browser doesn't support geolocation</p>";
return;
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var mapProp = {
center: new google.maps.LatLng(latitude, longitude),
zoom: 18,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow;
geocodeLatLng(geocoder, map, infowindow);
function geocodeLatLng(geocoder, map, infowindow) {
var input = latitude + "," + longitude;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(18);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
address.innerHTML = results[1].formatted_address;
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
you have a error here
use strict";
you should remove the "
And where you call your google map function ?

Google map api v3 - Event drag on marker is not trigger after a click event

I have a form with two input text for latitude and longitude.
If I drag and drop the marker on Google Map API, the values in the input will change.
If I click on the map, it will change too.
However, after this click event, the drag and drop animation and behavior is good but my event is never trigger, so the values do not change at all.
I found only one thread about 'drag and click conflicts' nevertheless any solution.
So, this is my code:
function launchMap(latitude, longitude, markerMap, zoom) {
mapLaunch = true;
var marker, map, latlng, image= '../Images/eolienne_marker_white.png', title = 'Site';
function initMap() {
var latlngOk = true;
if (latitude === null || latitude === 'undefined' || latitude == 'null') {
latlngOk = false;
}
if (longitude === null || longitude === 'undefined' || latitude == 'null') {
latlngOk = false;
}
if (latlngOk === true) {
latlng = new google.maps.LatLng(latitude, longitude);
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: latlng,
zoom: zoom,
draggable: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
if (markerMap === true) {
marker = new google.maps.Marker({
position: latlng,
icon: image,
map: map,
draggable: true,
title: title
});
}
}
google.maps.event.addDomListener(window, "resize", function () {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
google.maps.event.addListener(map, 'click', function (event) {
if (markerMap === true) {
marker.setMap(null);
}
markerMap = true;
marker = new google.maps.Marker({
position: event.latLng,
icon: image,
map: map,
draggable: true,
title: title
});
map.panTo(event.latLng);
document.getElementById('lat').value = event.latLng.lat();
document.getElementById('lng').value = event.latLng.lng();
});
google.maps.event.addListener(marker, 'drag', function (event) {
document.getElementById('lat').value = event.latLng.lat();
document.getElementById('lng').value = event.latLng.lng();
});
}
google.maps.event.addDomListener(window, "load", initMap);
}
Thanks for the help.
EDIT:
The solution is to add the drag event to each marker creating. In my code above there is one place where I create a marker without adding the Listener. You can see below the new code working great.
function launchMap(latitude, longitude, markerMap, zoom) {
mapLaunch = true;
var marker, map, latlng, image= '../Images/eolienne_marker_white.png', title = 'Site';
function initMap() {
var latlngOk = true;
if (latitude === null || latitude === 'undefined' || latitude == 'null') {
latlngOk = false;
}
if (longitude === null || longitude === 'undefined' || latitude == 'null') {
latlngOk = false;
}
if (latlngOk === true) {
latlng = new google.maps.LatLng(latitude, longitude);
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: latlng,
zoom: zoom,
draggable: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
if (markerMap === true) {
marker = new google.maps.Marker({
position: latlng,
icon: image,
map: map,
draggable: true,
title: title
});
// Call the new function for this first marker
googleMapsEventDrag(marker);
}
}
google.maps.event.addDomListener(window, "resize", function () {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
google.maps.event.addListener(map, 'click', function (event) {
if (markerMap === true) {
marker.setMap(null);
}
markerMap = true;
marker = new google.maps.Marker({
position: event.latLng,
icon: image,
map: map,
draggable: true,
title: title
});
// Call the new function for this second marker
googleMapsEventDrag(marker);
map.panTo(event.latLng);
document.getElementById('lat').value = event.latLng.lat();
document.getElementById('lng').value = event.latLng.lng();
});
}
google.maps.event.addDomListener(window, "load", initMap);
}
// New function (because calling multiple times)
function googleMapsEventDrag(marker){
google.maps.event.addListener(marker, 'drag', function (event) {
document.getElementById('lat').value = event.latLng.lat();
document.getElementById('lng').value = event.latLng.lng();
});
}
You're adding a drag event listener for the first marker you create. But that doesn't mean the markers you're creating in response to map clicks automatically inherit that drag event listener too. You need to add a separate event listener each time you add a marker in response to map clicks.
I think this should work:
function launchMap(latitude, longitude, markerMap, zoom) {
var marker, map, latlng, image= '../Images/eolienne_marker_white.png', title = 'Site';
function initMap() {
var latlngOk = true;
if (latitude === null || latitude === 'undefined' || latitude == 'null') {
latlngOk = false;
}
if (longitude === null || longitude === 'undefined' || latitude == 'null') {
latlngOk = false;
}
if (latlngOk === true) {
latlng = new google.maps.LatLng(latitude, longitude);
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: latlng,
zoom: zoom,
draggable: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
if (markerMap === true) {
marker = new google.maps.Marker({
position: latlng,
icon: image,
map: map,
draggable: true,
title: title
});
google.maps.event.addListener(marker, 'drag', markerDrag);
}
google.maps.event.addDomListener(window, "resize", function () {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
google.maps.event.addListener(map, 'click', function (event) {
if (markerMap === true) {
marker.setMap(null);
}
markerMap = true;
marker = new google.maps.Marker({
position: event.latLng,
icon: image,
map: map,
draggable: true,
title: title
});
map.panTo(event.latLng);
google.maps.event.addListener(marker, 'drag', markerDrag);
});
}
}
google.maps.event.addDomListener(window, "load", initMap);
}
function markerDrag(event) {
document.getElementById('lat').value = event.latLng.lat();
document.getElementById('lng').value = event.latLng.lng();
}

Move google maps marker on Places Auto-complete

I currently have a map that displays a marker on the users geolocation. I have a text input field set to Places Auto-complete. When a user searches a city name, a new marker is placed on the location. However, the old gelocation marker remains. I want to delete the old marker or move it so only 1 marker is on the map. How can I do this?
Here is my code:
<html>
<head>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 12
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Get GEOLOCATION
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
map.setCenter(pos);
var marker = new google.maps.Marker({
position: pos,
map: map,
draggable:true
});
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
map.setCenter(options.position);
}
// get places auto-complete when user type in location-text-box
var input = /** #type {HTMLInputElement} */(
document.getElementById('location-text-box'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29),
draggable:true
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon(/** #type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div>
<input type="text" id="location-text-box">
<div id="map-canvas"></div>
</div>
</body>
</html>
Make your marker global, and either hide it or move it to the new location
working code snippet:
var map;
var marker;
function initialize() {
var mapOptions = {
zoom: 12
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Get GEOLOCATION
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
map.setCenter(pos);
marker = new google.maps.Marker({
position: pos,
map: map,
draggable: true
});
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
map.setCenter(options.position);
marker = new google.maps.Marker({
position: options.position,
map: map,
draggable: true
});
}
// get places auto-complete when user type in location-text-box
var input = /** #type {HTMLInputElement} */
(
document.getElementById('location-text-box'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29),
draggable: true
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon( /** #type {google.maps.Icon} */ ({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''), (place.address_components[1] && place.address_components[1].short_name || ''), (place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places"></script>
<div style="height:100%; width:100%">
<input type="text" id="location-text-box" />
<div id="map-canvas"></div>
</div>
File javascript.js
function initialize() {
var mapOptions, map, marker, searchBox, city,
infoWindow = '',
addressEl = document.querySelector( '#map-search' ),
latEl = document.querySelector( '.latitude' ),
longEl = document.querySelector( '.longitude' ),
element = document.getElementById( 'map-canvas' );
city = document.querySelector( '.reg-input-city' );
mapOptions = {
// How far the maps zooms in.
zoom: 8,
// Current Lat and Long position of the pin/
center: new google.maps.LatLng( 23.0224, 72.5751 ),
// center : {
// lat: -34.397,
// lng: 150.644
// },
disableDefaultUI: false, // Disables the controls like zoom control on the map if set to true
scrollWheel: true, // If set to false disables the scrolling on the map.
draggable: true, // If set to false , you cannot move the map around.
// mapTypeId: google.maps.MapTypeId.HYBRID, // If set to HYBRID its between sat and ROADMAP, Can be set to SATELLITE as well.
// maxZoom: 11, // Wont allow you to zoom more than this
// minZoom: 9 // Wont allow you to go more up.
};
/**
* Creates the map using google function google.maps.Map() by passing the id of canvas and
* mapOptions object that we just created above as its parameters.
*
*/
// Create an object map with the constructor function Map()
map = new google.maps.Map( element, mapOptions ); // Till this like of code it loads up the map.
/**
* Creates the marker on the map
*
*/
marker = new google.maps.Marker({
position: mapOptions.center,
map: map,
draggable: true
});
/**
* Creates a search box
*/
searchBox = new google.maps.places.SearchBox( addressEl );
/**
* When the place is changed on search box, it takes the marker to the searched location.
*/
google.maps.event.addListener( searchBox, 'places_changed', function () {
var places = searchBox.getPlaces(),
bounds = new google.maps.LatLngBounds(),
i, place, lat, long, resultArray,
addresss = places[0].formatted_address;
for( i = 0; place = places[i]; i++ ) {
bounds.extend( place.geometry.location );
marker.setPosition( place.geometry.location ); // Set marker position new.
}
map.fitBounds( bounds ); // Fit to the bound
map.setZoom( 15 ); // This function sets the zoom to 15, meaning zooms to level 15.
// console.log( map.getZoom() );
lat = marker.getPosition().lat();
long = marker.getPosition().lng();
latEl.value = lat;
longEl.value = long;
resultArray = places[0].address_components;
// Get the city and set the city input value to the one selected
for( var i = 0; i < resultArray.length; i++ ) {
if ( resultArray[ i ].types[0] && 'administrative_area_level_2' === resultArray[ i ].types[0] ) {
citi = resultArray[ i ].long_name;
city.value = citi;
}
}
// Closes the previous info window if it already exists
if ( infoWindow ) {
infoWindow.close();
}
/**
* Creates the info Window at the top of the marker
*/
infoWindow = new google.maps.InfoWindow({
content: addresss
});
infoWindow.open( map, marker );
} );
/**
* Finds the new position of the marker when the marker is dragged.
*/
google.maps.event.addListener( marker, "dragend", function ( event ) {
var lat, long, address, resultArray, citi;
console.log( 'i am dragged' );
lat = marker.getPosition().lat();
long = marker.getPosition().lng();
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { latLng: marker.getPosition() }, function ( result, status ) {
if ( 'OK' === status ) { // This line can also be written like if ( status == google.maps.GeocoderStatus.OK ) {
address = result[0].formatted_address;
resultArray = result[0].address_components;
// Get the city and set the city input value to the one selected
for( var i = 0; i < resultArray.length; i++ ) {
if ( resultArray[ i ].types[0] && 'administrative_area_level_2' === resultArray[ i ].types[0] ) {
citi = resultArray[ i ].long_name;
console.log( citi );
city.value = citi;
}
}
addressEl.value = address;
latEl.value = lat;
longEl.value = long;
} else {
console.log( 'Geocode was not successful for the following reason: ' + status );
}
// Closes the previous info window if it already exists
if ( infoWindow ) {
infoWindow.close();
}
/**
* Creates the info Window at the top of the marker
*/
infoWindow = new google.maps.InfoWindow({
content: address
});
infoWindow.open( map, marker );
} );
});}

Categories

Resources