Creating a map with markers using the Google Maps API

I recently started working with the Google Maps API and wanted to add a marker to a specific location. I went through the documentation and attempted to implement it on my website, but encountered several undefined errors in the process. Here is the code snippet:

function initMap() {
// Map styled for night mode.
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 32.0225572, lng: 34.7766291},
zoom: 17,
mapTypeId: 'roadmap',
styles: [
{elementType: 'geometry', stylers: [{color: '#242f3e'}]},
{elementType: 'labels.text.stroke', stylers: [{color: '#242f3e'}]},
{elementType: 'labels.text.fill', stylers: [{color: '#746855'}]},
// More styling elements...
]
});
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
        var icons = {
          info: {
            icon: iconBase + 'info-i_maps.png'
          }
        };

        function addMarker(feature) {
          var marker = new google.maps.Marker({
            position: feature.position,
            icon: icons[feature.type].icon,
            map: map
          });
        }

        var feature = [
          {
            position: new google.maps.LatLng(32.0225572, 34.7766291),
            type: 'info'
          }];

          addMarker(feature);

}

// Additional marker information
var myLatLng = new google.maps.LatLng(32.0225572, 34.7766291);
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: iconBase + 'שטיק-לוגו-07.png'
});

function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
icon: icon,
map: map
});
}

var features = [
{
position: new google.maps.LatLng(32.0225572, 34.7766291),
type: 'info'
}
];

for (var i = 0, feature; feature = features[i]; i++) {
addMarker(feature);
}

https://jsfiddle.net/932j78og/1/

Answer №1

There were some errors in your code, but I managed to correct them and here is the final solution:

$(function() {
   var map = new google.maps.Map($("#map").get(0), {
    center: {lat: 32.0225572, lng: 34.7766291},
    zoom: 17,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    styles: [
    {elementType: 'geometry', stylers: [{color: '#242f3e'}]},
{elementType: 'labels.text.stroke', stylers: [{color: '#242f3e'}]},
{elementType: 'labels.text.fill', stylers: [{color: '#746855'}]},
{featureType: 'administrative.locality',elementType: 'labels.text.fill',stylers: [{color: '#d59563'}]},
        {featureType: 'poi', elementType: 'labels.text.fill', stylers: [{color: '#d59563'}]},
{featureType: 'poi.park',elementType: 'geometry',stylers: [{color: '#263c3f'}]},
 {featureType: 'poi.park',elementType: 'labels.text.fill',stylers: [{color: '#6b9a76'}]},
  {featureType: 'road',elementType: 'geometry',stylers: [{color: '#38414e'}]},
{featureType: 'road',elementType: 'geometry.stroke',stylers: [{color: '#212a37'}]},
{featureType: 'road',elementType: 'labels.text.fill',stylers: [{color: '#9ca5b3'}]},
{featureType: 'road.highway',elementType: 'geometry',stylers: [{color: '#746855'}]},
{featureType: 'road.highway',elementType: 'geometry.stroke',stylers: [{color: '#1f2835'}]},
{featureType: 'road.highway',elementType: 'labels.text.fill',stylers: [{color: '#f3d19c'}]},
{featureType: 'transit',elementType: 'geometry',stylers: [{color: '#2f3948'}]},
{featureType: 'transit.station',elementType: 'labels.text.fill',stylers: [{color: '#d59563'}]},
{featureType: 'water',elementType: 'geometry',stylers: [{color: '#17263c'}]},
{featureType: 'water',elementType: 'labels.text.fill',stylers: [{color: '#515c6d'}]},
{featureType: 'water',elementType: 'labels.text.stroke',stylers: [{color: '#17263c'}]}
    ]
  });
  var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
  var icons = {
    info: {
      icon: iconBase + 'info-i_maps.png'
    }
  };
  function addMarker(feature) {
    var marker = new google.maps.Marker({
      position: feature.position,
      icon: icons[feature.type].icon,
      map: map
    });
  }  
  
  // Your list of features
  var feature = [{
    position: new google.maps.LatLng(32.0225572, 34.7766291),
    type: 'info'
  }];  
  
  // Loop through each item in the array
  for(var i = 0; i < feature.length; i++) {
    // Adding a marker for each feature
    addMarker(feature[i]);  
  }
});
body {
  margin: 0;
  padding: 0;
  font: 12px sans-serif;
}

#map {
  width: 400px;
  height: 400px;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3&amp;sensor=false"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="map"></div>

Answer №2

One major issue in your fiddle (the code you uploaded contains multiple problems) is this JavaScript error:

Uncaught TypeError: Cannot read property 'icon' of undefined

The variable feature is an array without a ".type" property. Therefore, calling it in this manner:

addMarker(feature);

is incorrect. Instead, use this format:

addMarker(feature[0]);

This will work as intended.

Check out the updated fiddle here

#map {
  width: 100%;
  height: 300px;
}
<div id="map"></div>
<script>
  function initMap() {
    // Styles a map in night mode.
    var map = new google.maps.Map(document.getElementById('map'), {
      center: {
        lat: 32.0225572,
        lng: 34.7766291
      },
      zoom: 17,
      mapTypeId: 'roadmap',
      styles: styles
    });
    var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
    var icons = {
      info: {
        icon: iconBase + 'info-i_maps.png'
      }
    };

    function addMarker(feature) {
      var marker = new google.maps.Marker({
        position: feature.position,
        icon: icons[feature.type].icon,
        map: map
      });
    }

    var feature = [{
      position: new google.maps.LatLng(32.0225572, 34.7766291),
      type: 'info'
    }];

    addMarker(feature[0]);

  }
  var styles = [{
    elementType: 'geometry',
    stylers: [{
      color: '#242f3e'
    }]
  }, {
    elementType: 'labels.text.stroke',
    stylers: [{
      color: '#242f3e'
    }]
  }, {
    elementType: 'labels.text.fill',
    stylers: [{
      color: '#746855'
    }]
  }, /* more style properties... */
  ];
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDQn2RHysd7yzrxLD9UzeSilYJow1sjobY&callback=initMap"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update the ng-repeat attribute in HTML using either vanilla JavaScript or AngularJS

When the user clicks on the 'sort by book title' button, I want to change the ng-repeat="x in books' to ng-repeat="x in books|orderBy:'country'" in the HTML code. How can I achieve this action using JavaScript/Angular? Here is a ...

Incorporating JSON Objects within AngularJS

Currently, I am using AngularJS to fetch JSON data like this: $http.get('/balance').then(function (response) { $scope.balance = response.data; }); The value of response.data is as follows: { "pending": [{ "amount": 16, "currency": ...

Yarn is incapable of locating node modules

It has been some time since I last used yarn / npm, and now I am facing an issue while trying to configure a basic express server with yarn and typescript. The problem is that yarn is not properly "linking" my node_modules directory. I suspect that I may ...

What steps should I take to resolve the issue of "Uncaught Error: [News] is not a <Route> component. All components within <Routes> should be either a <Route> or <React.Fragment>"?

I'm having trouble with version 6 of react-router-dom while trying to create a news app. Can anyone help me with fixing it? When I use the following code, I encounter this error: Uncaught Error: [News] is not a component. All component children of ...

Using AJAX to submit a form and then refreshing the page within the current tab

I am facing an issue with my web page that contains multiple tabs, some of which have forms. Whenever a form is successfully submitted, the page reloads but always goes back to the default first tab. To address this, I am attempting to use a storage variab ...

Tips for sending form data from ReactJS to controller in ASP.NET MVC:

Seeking help with React and ASP.NET integration. I am attempting to create a form in ASP.NET using React, but encountering issues when trying to pass form data from ReactJS to an MVC ASP.NET controller. Below is the code that I have been working on. Any su ...

NodeAutoComplete: Enhanced Autocompletion for Node.js

I am attempting to utilize autocompletion of a JavaScript file with Node.js and Tern. However, the documentation for Ternjs is incredibly lacking. const tern = require("tern"); const ternServer = new tern.Server({}); const requestDetails = { "qu ...

If I do not utilize v-model within computed, then computed will not provide a value

I'm fairly new to coding in JS and Vue.js. I've been attempting to create a dynamic search input feature that filters an array of objects fetched from my API based on user input. The strange issue I'm coming across is that the computed metho ...

error: "undefined property cannot be read"

I am encountering an issue on our site where a bot is needed to work properly. The error message I am receiving is "cannot read property ´value´ of undefined". I have already set the bind_address to 0.0.0.0, but that did not resolve the issue (I also tri ...

Concealing a DisplayFor component with the help of Jquery

Hey there, I currently have a 'td' element that appears like this <td style="font-weight:bold"> @Html.DisplayFor(x => x.Parts[i].QtyInItem, new { htmlAttributes = new { @class = "qtyInItem" } }) </td> A ...

Is it possible to include three sorting states in jQuery DataTables: ASC, DESC, and NO_SORT?

When clicking on a column header in jQuery DataTables, the sorting order toggles between ascending (Down Arrow) and descending (Up Arrow). However, I am looking to customize this behavior: 1st-click ascending 2nd-click descending 3rd-click no-sorting 4th- ...

Javascript-generated HTML is malfunctioning as sliders are failing to slide

Currently learning Javascript and jQuery as I work on a one-page site using fullPage.js with data fetched from WordPress via JSON. The end goal is to convert this single-page site into a mobile app using cordova. Challenges: Utilizing the right/left slid ...

Monitoring Clicks within an Iframe

Is there a way to track a click event on a hyperlink within an iframe using Google Analytics? The iframe is located within the same domain as the main page. How can this be achieved? The iframe is added dynamically to the page after it has loaded. Is i ...

The functionality of AngularJS ng-disable is failing to work on an anchor tag

I am currently facing a challenge in my AngularJS project where I need to disable an icon within an ng-repeat scenario based on a condition. Specifically, I want to check if the owner is null and then disable the icon accordingly. However, despite verifyin ...

What is the reason that prototypes are not passed down through inheritance?

Can anyone shed light on why Validator.js is structured the way it is initialized (as shown in the first code snippet) and the reason behind the inability to call the validate method (as demonstrated in the second snippet)? I am currently experimenting wi ...

Are you struggling with NodeJS asynchronous callback not achieving success?

Currently, I am working on developing a scraper that utilizes the async.map feature to iterate through an array, perform certain logic, and then map them to different values. async.map($('.listing tr').toArray(), GetLink, function(err, results) ...

Edit content on the fly using ajax (add information to database)

I have a question that pertains to both UX and technical aspects. I am currently creating a list using ajax and PHP. I am unsure whether it is advisable to manipulate the DOM before the backend processes are complete. What potential issues could arise if ...

What is the best way to implement buttons dynamically in multiple divs created by Django using JavaScript loops?

I have been working on a Django project where I've created several HTML divs. My goal is to add a single button to each div. https://i.sstatic.net/DEIqL.png In the image provided, you can see a div with the class card-footer that I created using a Dj ...

Getting unique results from a knex.js INNER JOIN operation

Two tables, metadata and view_events, each have columns for config_id and config_type. The goal is to retrieve all unique view_events based on a user's email address, distinct by config_id and config_type, ordered by timestamp in descending order, lim ...

What is the best way to format the information when using response.send() in express.js?

I need help with customizing the content I'm returning in the app.post() method. Is there a way to do this? Below is an example of the app.post() code: app.post("/",function(req,res){ const query = req.body.cityName; const cityName = query.charA ...